每个循环中的项目都没有定义?

时间:2018-01-29 20:05:54

标签: javascript

我正在查看答案here,但在做的时候:

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

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

我收到错误:

item is not defined

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

object.splice(index, 1);

3 个答案:

答案 0 :(得分:9)

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

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));

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

-b master

这样做意味着您传递给函数--users.forEach(item, index, object => { /* ... */ }) 和带有单个参数item的箭头函数(单个参数不需要括号)。 改为:

index

这会传递一个包含3个参数的箭头函数:object是当前项users.forEach((item, index, object) => { /* ... */ }) - 索引item - 调用对象index - 这种情况object