【问题标题】:Item is not defined in a for each loop?项目不是在 for each 循环中定义的吗?
【发布时间】:2018-07-08 14:44:53
【问题描述】:

我正在查看答案here,但是在这样做时:

let users = [{name: 'john', address: '10 king street'}, ....];

users.forEach(item, index, object => {

我得到错误:

item is not defined

我需要这个,所以我可以:

object.splice(index, 1);

【问题讨论】:

标签: javascript


【解决方案1】:

向箭头函数传递多个参数时,将它们括在括号中:

users.forEach((item, index, object) => { ... }

(见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Syntax

例如,要删除所有名为“john”的用户,请执行以下操作:

users.forEach((item, index, object) => {
  if(item.name == 'john') {
    object.splice(index, 1);
  }
});

片段:

let users = [
  {name: 'john', address: '10 king street'},
  {name: 'mary', address: '10 queen street'},
  {name: 'john', address: '10 prince street'},
  {name: 'hank', address: '10 duke street'}
];

users.forEach((item, index, object) => {
  if(item.name == 'john') {
    object.splice(index, 1);
  }
});

console.log(JSON.stringify(users));

【讨论】:

  • 谢谢,item和object有什么区别?
  • @panthro 阅读文档,item 是当前迭代的 item,object 是整个数组
【解决方案2】:

您需要将所有参数放入括号中,例如:

users.forEach((item, index, object) => {

【讨论】:

    【解决方案3】:

    您忘记将箭头函数的参数括在括号中。

    users.forEach(item, index, object => { /* ... */ })
    

    这样做意味着您传递给函数itemindex 和一个带有单个参数object 的箭头函数(单个参数不需要括号)。 改为:

    users.forEach((item, index, object) => { /* ... */ })
    

    这将传递一个带有 3 个参数的箭头函数:item 是当前项,index - 索引,object - 对象 forEach 被调用 - 在本例中为 users

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 2011-10-08
      相关资源
      最近更新 更多