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

时间:2022-01-20 21:21:59
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/

10 个解决方案

#1


25  

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"]

#2


7  

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

#3


3  

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 );

#4


2  

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]);
  }
}

#5


1  

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

6.4. Enumeration

Since JavaScript's arrays are really objects, the for in statement can be used to iterate over all of the properties of an array. Unfortunately, for in makes 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语句可用于迭代数组的所有属性。不幸的是,因为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]);
}

#6


1  

You could also use a filter:

您还可以使用过滤器:

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

#7


0  

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

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

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

#8


0  

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"]

#9


0  

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: "Jack" }, 
  { id: 4, name: "Averell" } 
];

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

console.log(daltons);

#10


-1  

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

请享用

#1


25  

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"]

#2


7  

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

#3


3  

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 );

#4


2  

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]);
  }
}

#5


1  

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

6.4. Enumeration

Since JavaScript's arrays are really objects, the for in statement can be used to iterate over all of the properties of an array. Unfortunately, for in makes 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语句可用于迭代数组的所有属性。不幸的是,因为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]);
}

#6


1  

You could also use a filter:

您还可以使用过滤器:

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

#7


0  

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

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

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

#8


0  

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"]

#9


0  

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: "Jack" }, 
  { id: 4, name: "Averell" } 
];

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

console.log(daltons);

#10


-1  

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

请享用