javascript 如何从javascript中的foreach循环中删除特定的数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11058384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:57:21  来源:igfitidea点击:

How to delete specific array elements from within a foreach loop in javascript

javascriptarrays

提问by Nick

var fruit = ["apple","pear","pear","pear","banana"];

How do I remove all "pear" fruit from this array?
I tried the following, but still one pear remains:

如何从此数组中删除所有“梨”水果?
我尝试了以下方法,但仍然留下一个梨:

for(var f in fruit) {
    if ( fruit[f] == "pear" ) {
        fruit.splice(f, 1);
    }
}

for(var f in fruit) {
    document.write(fruit[f]+"<br>");        
}

Outputs:

输出:

apple 
pear 
banana

?What am I doing wrong? Live demo: http://jsfiddle.net/SbxHc/

?我究竟做错了什么?现场演示:http: //jsfiddle.net/SbxHc/

回答by Esailija

var fruit = ["apple", "pear", "pear", "pear", "banana"],
    i;

for (i = 0; i < fruit.length; ++i) {
    if (fruit[i] === "pear") {
        fruit.splice(i--, 1);
    }
}

console.log(fruit);
//["apple", "banana"]

回答by Tom

for (var i = fruit.length - 1; i > -1; i--) {
    if (fruit[i] == "pear")
        fruit.splice(i, 1);
}

回答by Tuan

When you remove items from an array as you iterate over it, you would generally iterate backwards so that the current index doesn't skip over items as you remove them:

当您在迭代数组时从数组中删除项目时,您通常会向后迭代,以便当前索引在您删除项目时不会跳过项目:

var fruit = ["apple","pear","pear","pear","banana"];
var i;

for (i = fruit .length - 1; i >= 0; i--) {
    if (fruit [i] === "pear") {
        fruit .splice(i, 1);
    }        
}

console.log(fruit );

回答by raina77ow

If there are plenty of 'wrong' elements in the original array, I suggest at least considering not using in-place array, instead collecting all the 'right' elements into a new array:

如果原始数组中有很多“错误”元素,我建议至少考虑不使用就地数组,而是将所有“正确”元素收集到一个新数组中:

var rightFruits = [];
for (var i = 0, len = fruit.length; i < len; ++i) {
  if (fruit[i] !== 'pear') {
    rightFruits.push(fruit[i]);
  }
}

回答by user278064

var i;
for (i = 0; i < fruits.length; i += 1) {
   if (fruits[i] == "pear") {
      fruits.splice(i, 1);
      i -= 1;
   }
}

6.4. Enumeration

6.4. 枚举

Since JavaScript's arrays are really objects, the for instatement can be used to iterate over all of the properties of an array. Unfortunately, for inmakes no guarantee about the order of the properties, and most array applications expect the elements to be produced in numerical order. Also, there is still the problem with unexpected properties being dredged up from the prototype chain.

由于 JavaScript 的数组实际上是对象,因此该for in语句可用于迭代数组的所有属性。不幸的是,for in不能保证属性的顺序,大多数数组应用程序都希望元素按数字顺序生成。此外,仍然存在从原型链中挖掘出意外属性的问题。

Fortunately, the conventional for statement avoids these problems. JavaScript's for statement is similar to that in most C-like languages. It is controlled by three clauses: the first initializes the loop, the second is the while condition, and the third does the increment:

幸运的是,传统的 for 语句避免了这些问题。JavaScript 的 for 语句类似于大多数类 C 语言中的语句。它由三个子句控制:第一个初始化循环,第二个是 while 条件,第三个执行增量:

var i;
for (i = 0; i < myArray.length; i += 1) {
   document.writeln(myArray[i]);
}

回答by user278064

You could also use a filter:

您还可以使用filter

let noPears = fruits.filter(fruit => fruit != 'pear')

回答by Lain inVerse

var i; while ((i = fruit.indexOf("pear")) > -1) fruit.splice(i,1);

Be aware that Array.indexOf is not supported by IE8 and below. -_-

请注意 Array.indexOf 不受 IE8 及以下版本的支持。-_-

回答by rodrigo-silveira

Why not iterate the list backwards? That way, when you delete an element from the list and the length changes, it doesn't break the loop logic:

为什么不向后迭代列表?这样,当您从列表中删除一个元素并且长度发生变化时,它不会破坏循环逻辑:

var fruit = ["apple","pear","pear","pear","banana"];
for (var i = fruit.length - 1; i >= 0; i--) {
    if (fruit[i] === "pear") {
        fruit.splice(i, 1);
    }
}

console.log(fruit); // ["apple", "banana"]

回答by Jobacca

If it doesn't care to iterate reverse, you can use a combination of while and array's pop-function

如果不关心反向迭代,可以结合使用while和array的pop-function

var daltons = [ 
  { id: 1, name: "Joe" }, 
  { id: 2, name: "William" }, 
  { id: 3, name: "Hyman" }, 
  { id: 4, name: "Averell" } 
];

var dalton;
while (dalton=daltons.pop()) {
  console.log(dalton.name);
}

console.log(daltons);

回答by Dan Barzilay

for(var f in fruit) {
    if ( fruit[f] == "pear" ) {
        fruit.splice(f-1, 1);
    }
}

for(var f in fruit) {
    document.write(fruit[f]+"<br>");        
}

enjoy

请享用