从传递给forEach的回调中拼接Javascript数组

我有这段代码,它应该遍历数组中的每个项目,并根据某些条件删除项目:

//iterate over all items in an array

//if the item is "b", remove it.

var array = ["a", "b", "c"];

array.forEach(function(item) {

if(item === "b") {

array.splice(array.indexOf(item), 1);

}

console.log(item);

});

所需的输出:

a

b

c

实际输出:

a

b

显然,本机的forEach方法不会在每次迭代后检查是否已删除该项目,因此,如果已删除则将跳过下一个项目。除了重写forEach方法或实现我自己的类以代替数组使用之外,还有其他更好的方法吗?

编辑-根据我的评论,我想解决方案是仅使用标准的for循环。如果您有更好的方法,请随时回答。

回答:

让我们看看为什么JavaScript会这样表现。根据ECMAScript标准规范Array.prototype.forEach

当您删除索引1处的元素时,索引2处的元素将成为索引1处的元素,而该对象的索引2不存在。

现在,JavaScript在对象中查找未找到的元素2,因此它跳过了函数调用。

这就是为什么您只看到a和的原因b


实际的方法是使用 Array.prototype.filter

var array = ["a", "b", "c"];

array = array.filter(function(currentChar) {

console.log(currentChar); // a, b, c on separate lines

return currentChar !== "b";

});

console.log(array); // [ 'a', 'c' ]

以上是 从传递给forEach的回调中拼接Javascript数组 的全部内容, 来源链接: utcz.com/qa/397668.html

回到顶部