最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Item is not defined in a for each loop? - Stack Overflow

programmeradmin5浏览0评论

I'm looking at the answer here but when doing:

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

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

I get the error:

item is not defined

I need this so I can:

object.splice(index, 1);

I'm looking at the answer here but when doing:

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

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

I get the error:

item is not defined

I need this so I can:

object.splice(index, 1);
Share Improve this question asked Jan 29, 2018 at 20:05 panthropanthro 24.1k70 gold badges205 silver badges350 bronze badges 2
  • 3 your syntax seems wrong. Try users.forEach((item, index, object) => { – Chris Commented Jan 29, 2018 at 20:07
  • You're using foreach incorrectly. It's first argument is a function. developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – jpaugh Commented Jan 29, 2018 at 20:08
Add a ment  | 

3 Answers 3

Reset to default 9

When passing multiple parameters to an arrow function, enclose them in parentheses:

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

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

For example, to remove all users named "john," do this:

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

Snippet:

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

you need to put all the params into parenthesis like :

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

You forgot to enclose the parameters to the arrow function in parentheses.

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

Doing this means you pass to the function item, index, and an arrow function with a single param object(parentheses not needed with a single param). Change to this:

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

This will pass an arrow function with 3 params: item is the current item, index - the index, object - the object forEach was called on - in this case users.

发布评论

评论列表(0)

  1. 暂无评论