Javascript 从数组中删除所有虚假值

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

Remove all falsy values from an array

javascriptarrays

提问by Vignesh

I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

我想从数组中删除所有虚假值。JavaScript 中的假值是 false、null、0、""、undefined 和 NaN。

function bouncer(arr) {
 arr = arr.filter(function (n) { 
    return (n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && isNaN()!=NaN); });
  return arr;
}

bouncer([7, "ate", "", false, 9, NaN], "");

The above is getting satisfied for all except the NaN test case. Can someone help me check in the array whether it contains NaN or not?

除了 NaN 测试用例之外,以上所有内容都得到满足。有人可以帮我检查数组是否包含 NaN 吗?

回答by LoremIpsum

You can use Boolean :

您可以使用布尔值:

var myFilterArray = myArray.filter(Boolean);

回答by Pointy

Since you want to get rid of "falsy" values, just let JavaScript do its thing:

既然你想摆脱“假”值,就让 JavaScript 做它的事情:

function bouncer(arr) {
  return arr.filter(function(v) { return !!v; });
}

The double-application of the !operator will make the filter callback return truewhen the value is "truthy" and falsewhen it's "falsy".

!运算符的双重应用 将使过滤器回调true在值为“真”和“假”false时返回。

(Your code is calling isNaN()but not passing it a value; that's why that test didn't work for you. The isNaN()function returns trueif its parameter, when coerced to a number, is NaN, and falseotherwise.)

(您的代码正在调用isNaN()但未传递值;这就是该测试对您不起作用的原因。如果其参数在强制为数字时为,则该isNaN()函数返回,否则返回。)trueNaNfalse

edit— note that

编辑- 请注意

function bouncer(arr) {
  return arr.filter(Boolean);
}

would work too as LoremIpsum notes in another answer, because the built-in Boolean constructor does pretty much the exact same thing as !!.

也可以像 LoremIpsum 在另一个答案中指出的那样工作,因为内置的布尔构造函数与!!.

回答by J__

truthyArray = arr.filter(el => el)

^ that's how you do it

^ 你就是这样做的

回答by ioncreature

You use isNaN()in wrong way. It should be something like following:

你用isNaN()错了。它应该类似于以下内容:

function bouncer(arr) {
   return arr.filter(function (n) { 
       return n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && !isNaN(n); 
   });

}

}

Also you can rewrite it:

你也可以重写它:

function bouncer( arr ){
    return arr.filter( function( value ){
        return value;
    });
}

回答by Andión

Using this simple filter will do:

使用这个简单的过滤器可以:

array.filter(Boolean)

array.filter(Boolean)

You can read more about Booleanhere

你可以在这里阅读更多Boolean

回答by sealocal

This is another equivalent, but illustrative, solution:

这是另一个等效但说明性的解决方案:

function bouncer( arr ){
    return arr.filter( function( value ){
        return value ? true : false;
    });
}

This code sample is illustrative because it indicates to a reader that the variable valuewill be evaluated as truthy or falsey, and the anonymous function will return a boolean, either trueor false, mapping to the evaluation of value.

此代码示例是说明性的,因为它指示到读取器,该可变value会truthy或falsey和匿名函数将返回一个布尔值,来评价truefalse,映射的评价value

For someone who is not familiar with this approach of removing values from an array based on their truthiness, or for someone who is not familiar with (or has not read the documentation on) the filterfunction, this example is the most concise that still conveys the behavior of the filterfunction.

对于不熟悉这种基于真实性从数组中删除值的方法的人,或者对于不熟悉(或未阅读相关文档)该filter函数的人来说,这个例子是最简洁的,仍然传达了filter函数的行为。

Of course, in your application you may opt for the more concise, yet less insightful, implementation:

当然,在您的应用程序中,您可以选择更简洁但缺乏洞察力的实现:

function bouncer( arr ){
    return arr.filter( function( value ){
        return value;
    });
}

回答by sealocal

I know this can be done using the arr.filter() method. But I prefer using the Boolean() function. Is clearer to me. Here's how I did it, although a little longer:

我知道这可以使用 arr.filter() 方法来完成。但我更喜欢使用 Boolean() 函数。对我来说更清楚。这是我的做法,虽然有点长:

function bouncer(arr) {
// Don't show a false ID to this bouncer.

    var falsy;
    var trueArr = [];

    for (i = 0; i < arr.length; i++) {

        falsy =  Boolean(arr[i]);

        if (falsy === true) {

        trueArr.push(arr[i]);

        }

    }

    return trueArr;
}

bouncer([7, "ate", "", false, 9]);
// returns a new array that is filtered accordingly.

回答by Chhitij Srivastava

Using filter we can write

使用过滤器我们可以写

function bouncer(arr) {
 return arr.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]) // will return [].

回答by Kirill Kotlyarov

I think a better deal this way

我认为这样更划算

   function bouncer(arr) {
        arr = arr.filter(function(item) {
            return item;
        return arr;

    bouncer([7, "ate", "", false, 9, NaN, undefined, 0]);

回答by Jalal Azimi

bouncer function:

保镖功能:

function bouncer(arr) {
  return arr.filter((val) => {
    return !!val;
  });
}

console.log(bouncer([7, "ate", "", false, 9]));