gpt4 book ai didi

javascript - Item 未在 foreach 循环中定义?

转载 作者:行者123 更新时间:2023-11-28 11:11:36 24 4
gpt4 key购买 nike

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

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

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

我收到错误:

item is not defined

我需要这个,这样我就可以:

object.splice(index, 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));

关于javascript - Item 未在 foreach 循环中定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48509154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com