javascript .filter() 真正的布尔值 [英] javascript .filter() true booleans

查看:15
本文介绍了javascript .filter() 真正的布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
    function a(b) {
      if(b !== false) {
        return b;
      }
    }

    arr = arr.filter(a);
    return arr;
}

bouncer([7, 'ate', '', false, 9]);

我只需要返回真正的布尔语句,当我运行这段代码时,它就可以工作了.但是,我很困惑,因为我的if 语句"无论是 b !== true 还是 b !== false 都会起作用.有人可以解释一下为什么这两种方式都有效吗?

I have to return true boolean statements only, and when I run this code, it works. However, I am quite confused because my "if statement" will work whether it's b !== true or b !== false. Could someone please explain the reason why this works both ways?

推荐答案

显然 .filter() 是在 ES5 中引入的.

Apparently .filter() was introduced in ES5.

这无疑帮助我了解了这里发生的事情.希望对您有所帮助!

This definitely helped me wrap my mind around what's going on here. Hope it helps!

基本上,写作:

arr.filter(Boolean)

同写:

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

因为 Boolean() 也是一个函数,当为真时返回真,当为假时返回假!

since Boolean() is also a function that returns truthy when true and falsy when false!

例子:

var a = [1, 2, "b", 0, {}, "", NaN, 3, undefined, null, 5];

var b = a.filter(Boolean);  // [1, 2, "b", {}, 3, 5]; 

来源:这里.

这篇关于javascript .filter() 真正的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆