javascript - 解释数组 - 连接到特定对象
问题描述
我目前正在学习 JavaScript,并且正在做一些关于数组的练习。我无法理解下面代码中的“用户”如何访问数组中每个对象的所有“用户名”。
这是我的数组的一个示例:
//array
const array = [{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},
];
//exercise where I cant undestand how user parameter acces username from objects
const filterArray = array.filter(user => {
return user.team === "red";
})
console.log(filterArray);
解决方案
阅读filter()
.
该
filter()
方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
在您的代码中,user
是 的回调函数的参数filter
。JavaScript 使用数组的每个元素调用此函数,因此user
接收数组中项目的所有详细信息。
推荐阅读
- swift - Swift对象在打印不同时没有成员
- arduino - 如何在 Arduino 中正确使用 Wire.onReceive
- c# - 在实体框架中编辑对象时出错实体对象不能被实体更改跟踪器的多个实例引用
- c - 如果 CPU 看到虚拟地址,页面错误处理程序如何用物理地址填充页表条目?
- javascript - selectionSort Javascript 动画
- python - 解析标记文件python
- python - 如何创建一个虚拟的双循环链表python?
- html - 在页面加载时从 url 列表中选择一个随机 .mp3 文件以自动播放?
- wcf - 请求被中止:无法创建 SSL/TLS 安全通道 - 没有证书
- r - gsub无法删除R中的空括号