首页 > 解决方案 > 解释数组 - 连接到特定对象

问题描述

我目前正在学习 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);

标签: javascriptarrays

解决方案


阅读filter().

filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

在您的代码中,user是 的回调函数的参数filter。JavaScript 使用数组的每个元素调用此函数,因此user接收数组中项目的所有详细信息。


推荐阅读