使用 JavaScript 从数组中删除零值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5817756/
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-25 18:27:43  来源:igfitidea点击:

Delete zero values from Array with JavaScript

javascriptarrays

提问by vissu

I have an array with name "ids" and some values like ['0','567','956','0','34']. Now I need to remove "0" values from this array. ids.remove ("0");is not working.

我有一个名为“ids”的数组和一些值,如 ['0','567','956','0','34']。现在我需要从这个数组中删除“0”值。 ids.remove ("0"); 不管用。

回答by Harry Joy

Use splice method in javascript. Try this function:

在 javascript 中使用 splice 方法。试试这个功能:

function removeElement(arrayName,arrayElement)
 {
    for(var i=0; i<arrayName.length;i++ )
     { 
        if(arrayName[i]==arrayElement)
            arrayName.splice(i,1); 
      } 
  }

Parameters are:

参数是:

arrayName:-      Name of the array.
arrayElement:-   Element you want to remove from array

回答by jesal

Here's one way to do it:

这是一种方法:

['0','567','956','0','34'].filter(Number)

回答by Tim Down

Here's a function that will remove elements of an array with a particular value that won't fail when two consecutive elements have the same value:

这是一个函数,它将删除具有特定值的数组元素,当两个连续元素具有相同值时,该元素不会失败:

function removeElementsWithValue(arr, val) {
    var i = arr.length;
    while (i--) {
        if (arr[i] === val) {
            arr.splice(i, 1);
        }
    }
    return arr;
}

var a = [1, 0, 0, 1];
removeElementsWithValue(a, 0);
console.log(a); // [1, 1]

In most browsers (except IE <= 8), you can use the filter()method of Array objects, although be aware that this does return you a new array:

在大多数浏览器中(IE <= 8 除外),您可以使用filter()Array 对象的方法,但请注意,这确实会返回一个新数组:

a = a.filter(function(val) {
    return val !== 0;
});

回答by Adria

For non-trivial size arrays, it's still vastly quicker to build a new array than splice or filter.

对于非平凡大小的数组,构建新数组仍然比拼接或过滤器快得多。

var new_arr = [],
tmp;

for(var i=0, l=old_arr.length; i<l; i++)
{
  tmp = old_arr[i];

  if( tmp !== '0' )
  {
    new_arr.push( tmp );
  }
}

If you do splice, iterate backwards!

如果您进行拼接,请向后迭代!

回答by Adrian Swifter

For ES6 best practice standards:

对于 ES6 最佳实践标准:

let a = ['0','567','956','0','34'];


a = a.filter(val => val !== "0");

(note that your "id's" are strings inside array, so to check regardless of type you should write "!=")

(请注意,您的“id”是数组内的字符串,因此要检查您应该编写的任何类型的“!=”)

回答by Ammu

Below code can solve your problem

下面的代码可以解决你的问题

 for(var i=0; i<ids.length;i++ )
 { 
    if(ids[i]=='0')
        ids.splice(i,1); 
  } 

回答by avoliva

ids.filter(function(x) {return Number(x);});