array.splice从剩余元素中删除值 [英] array.splice removing values from remaining elements

查看:35
本文介绍了array.splice从剩余元素中删除值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了array.splice的这种奇怪的副作用,并将代码精简到重新创建所需的最低限度.是的,很多事情可以通过array.filter在一行上完成,但是我对我是否犯了错误或是否正在发生其他事情很感兴趣.

I ran across this strange side effect of array.splice, and distilled the code down to the minimum necessary to recreate. Yes, much of this could be done on one line with array.filter, but I'm interested in whether I've made a mistake or if something else is going on.

var array = [];

for (var i = 0; i < 10; i++) {
  array.push({
    value: i
  });
}

array.forEach(function(item, index, intArray) {
  if (item.value % 2 == 1) {
    item.odd = true;
  } else {
    item.odd = false;
  }

  if (item.odd) {
    console.log("Removing " + item.value);
    intArray.splice(index, 1);
  }

});

console.log(array);

运行此JavaScript会导致按预期方式删除了奇数元素,但同时也删除了项2、4、6和8的item.odd值.删除intArray.splice行会带回奇数数组元素,但是它还会带回所有元素的item.odd值.

Running this javascript results in the odd elements being removed as expected, but it also removed the item.odd values for items 2, 4, 6, and 8. Removing the intArray.splice line brings back the odd array elements, but it also brings back the item.odd values for all elements.

我已经在FF和Chrome中对此进行了测试.即使只有该项被传递到回调中,行为仍然存在,其索引是通过array.indexOf计算的,并从循环外部引用该数组.

I've tested this in FF and Chrome. The behavior persists even if only the item is passed into the callback, with the index calculated via array.indexOf, and referencing the array from outside the loop.

推荐答案

我认为,当您在每个奇数处拼接数组时, forEach 最终跳过了下一项.偶数.因此,这些项目根本不会被修改.

I think that when you splice the array at every odd number, the forEach ends up skipping over the next item, which is an even number. So those items don't get modified at all.

var array = [];

for (var i = 0; i < 10; i++) {
  array.push({
    value: i
  });
}

array.forEach(function(item, index, intArray) {
  console.log(item); // only prints out 0, 1, 3, 5, 7, 9

  if (item.value % 2 == 1) {
    item.odd = true;
  } else {
    item.odd = false;
  }

  if (item.odd) {
    console.log("Removing " + item.value);
    intArray.splice(index, 1);
  }

});

console.log(array);

换句话说, forEach 仅访问每个索引一次.因此,可以说它到达索引1的项目1.它删除了项目1.项目2现在位于索引1.但是索引1已经被访问过,因此它移到索引2处的项目,现在是索引1.3.

In other words, forEach only visits each index once. So say it gets to item 1, which is at index 1. It deletes item 1. Item 2 is now at index 1. But index 1 has already been visited, so it moves on to the item at index 2, which is now item 3.

这篇关于array.splice从剩余元素中删除值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆