JavaScript 不会在一次迭代中移除所有元素,即使条件总是满足

JavaScript does not remove all elements in one iteration, even when the condition is always satisfied

我正在尝试比较两个包含多个对象的数组,并根据条件删除元素。我首先在 chrome 的控制台中尝试,并且出于某种原因震惊地发现,即使我使用的 if 条件显然始终为真,arr1 也没有变空。在第一次迭代之后,我总是看到至少有一个对象被遗漏,并且在 运行 循环多次之后,它被删除了。我错过了什么吗?这似乎是一个基本的 JavaScript 错误。

var car1 = {
  type: 'das',
  model: '1',
  color: 'blue'
} //sample object
arr1 = []
for (i = 0; i < 5; i++) {
  arr1[i] = car1
} //filling object with values

for (i in arr1) {
  if (arr1[i].type == 'das') { //removing element with condition which always matches
    arr1.splice(i, 1);
  }
}
console.log(arr1);

您不能在其循环中更改数组值。

var car1 = {
  type: 'das',
  model: '1',
  color: 'blue'
} //sample object
arr1 = []
for (i = 0; i < 5; i++) {
  arr1[i] = car1
} //filling object with values
arr2 = [];
for (i in arr1) {
  if (arr1[i].type != 'das') { //removing element with condition which always matches
    arr2.push(arr1[i]);
  }
}
arr1 = arr2
console.log(arr1);