每个环路的拼接工作不正常

Splice on forEach loop not working properly

本文关键字:工作 不正常 拼接 环路      更新时间:2023-12-10

我有以下上下文:

https://jsfiddle.net/eqntaqbt/2/

obj.forEach(function(user, index){
    var userName = user.name;
    console.log(index, userName);
  if(index === 5 || index === 2){
    obj.splice(index, 1);
  }
});

我正在使用forEach循环和splice来移除obj阵列上位置52中的项。但由于某种原因,它不能正常工作。

我做错了什么?

您的代码在循环时正在拼接。即使已不存在拼接的图元,也会对其进行访问。这导致了未定义的元素。

您可以考虑Array#filter

var obj = [{ "index": 0, "name": "Odonnell Noble", "gender": "male", "company": "DIGIQUE", "eail": "odonnellnoble@digique.com" }, { "index": 1, "name": "Marie Oneal", "gender": "female", "company": "CANOPOLY", "email": "marieoneal@canopoly.com" }, { "index": 2, "name": "Adrienne Marsh", "gender": "female", "company": "XOGGLE", "email": "adriennemarsh@xoggle.com" }, { "index": 3, "name": "Goff Mullins", "gender": "male", "company": "ENDIPIN", "email": "goffmullins@endipin.com" }, { "index": 4, "name": "Lucile Finley", "gender": "female", "company": "AQUASSEUR", "email": "lucilefinley@aquasseur.com" }, { "index": 5, "name": "Pitts Mcpherson", "gender": "male", "company": "QUARX", "email": "pittsmcpherson@quarx.com" }];
obj = obj.filter(function (user, index) {
    return (user.index !== 5 && user.index !== 2);
});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

每个的数组#

forEach()处理的元素范围设置在第一个回调调用。之后附加到数组的元素对forEach()开始的调用将不会被回调访问。如果数组中现有元素的值发生更改,传递的值to回调将是Each()访问它们时的值;在访问之前删除的元素不会被访问

obj.forEach(function(user, index){
    var userName = user.name;
    //console.log(index, userName);
  if(user.index === 5 || user.index === 2){
    this.splice(index, 1);
  }
}.bind(obj));

这是工作小提琴

forEach是指所谓的副作用。

代码的问题是,在迭代数组时要更改数组。因此,如果删除一个项,则会立即重新分配数组的所有其他索引。这就是为什么在移除一个项目后,进一步的移除不会做所需的事情(在所需的位置)。

所以forEach有利于影响实际数组之外的东西,即迭代。

对于一个叫做filter的函数来说,这将是一个完美的用例,因为这实际上就是你对列表所做的:你想过滤掉一些项目。

array = array.filter(function(item, index) {
   return (index !== 5 && index !== 2)
}

Filter将函数作为参数排除在外,该函数本身将为数组中的每个项调用。如果某个项的函数返回true,则保留该项,否则将删除该项。这就是为什么这里的逻辑表达式必须稍微更改:它读起来像:保留不属于索引5和索引2的项。这些类型的true或false返回函数称为谓词。

如果你想过滤掉更多的索引呢?使用locical运算符的表达式很快变得相当长。

相反,您可以在索引列表上使用数组方法indexOf,每次都将数组的当前索引传递给它。这将返回a位置,如果不在其中,则返回-1。在以后的情况下,您希望将项保留在数组中。

array = array.filter(function(item, current_index) {
   return ([2, 5].indexOf(current_index) === -1)
}

此外,您可以将其封装在一个函数中:

function removeIndices(array, indices) {
   return array.filter(function(item, current_index) {
      return (indices.indexOf(current_index) === -1)
   })
}

最后:

array = removeIndices(array, [2, 5]);