此刻我正在学习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);
答案 0 :(得分:2)
阅读filter()
的文档。
filter()
方法将创建一个新数组,其中包含所有通过提供的功能实现的测试的元素。
在您的代码中,user
是filter
的回调函数的参数。 JavaScript会使用数组的每个元素调用此函数,因此user
会接收数组中各项的所有详细信息。
答案 1 :(得分:1)
.filter
方法将逐一遍历数组中的每个元素,并将应用您赋予它的函数(在您的情况下为user => user.team === 'red'
)以确定该元素是否应为是否在结果数组中。
将其视为内置的书写方式:
function filter(array){
let result = [];
for (let i = 0; i < array.length; i++){
if (array[i].team === 'red'){
result.push(array[i]);
}
}
return result;
}