简体   繁体   English

如何从JavaScript中的数组中删除某些数字元素

[英]How to remove certain number elements from an array in javascript

var numbers = [1,2,0,3,0,4,0,5];

If I have the above array and I want to remove the 0s and output an array of [1,2,3,4,5] how would I do it? 如果我有上述数组,并且想删除0并输出[1,2,3,4,5]数组,我该怎么做?

I have the below code but I am getting an "TypeError: arr.includes is not a function" error... 我有以下代码,但出现“ TypeError:arr.includes不是函数”错误...

var zero = 0;

var x = balDiffs.map(function(arr, i) {
  console.log(arr);
  if(arr.includes(zero)) {
    return i;
  }
});

Use Array#filter with Boolean function as the callback. 使用带有布尔函数的Array#filter作为回调。 The Boolean function will return false for 0, and true for other numbers: 布尔函数将返回false为0, true为其他数字:

 var numbers = [1,2,0,3,0,4,0,5]; var result = numbers.filter(Boolean); console.log(result); 

Array#map returns an array with the same length as the given array, but it can change the values of each element. Array#map返回长度与给定数组相同的数组,但是它可以更改每个元素的值。

Then you took an element for Array#includes or String#includes but that does not work with numbers. 然后,您将一个元素用于Array#includesString#includes但不适用于数字。

But even if that works, you would get only zeroes and undefined with the given approach. 但是,即使这行得通,使用给定的方法也只会得到零且未undefined


You could use Array#filter and filter the unwanted value. 您可以使用Array#filter并过滤不需要的值。

 var numbers = [1, 2, 0, 3, 0, 4, 0, 5], value = 0, // or any other value filtered = numbers.filter(v => v !== value); console.log(filtered); 

Approach with more than one unwanted value. 具有多个不想要的值的方法。

 var numbers = [1, 2, 0, 3, 0, 4, 0, 5], unwanted = [0, 3], filtered = numbers.filter(v => !unwanted.includes(v)); console.log(filtered); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM