JavaScript的.filter()方法如何过滤出true布尔值?

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

我只需要返回true布尔语句,当我运行这段代码时,它可以正常工作。然而,我相当困惑,因为我的“if语句”无论是b !== true还是b !== false都可以工作。请问有人能解释一下为什么会这样吗?


1
删除Javascript数组中的空元素。 - vsync
真是令人惊讶,在这里有这么多人甚至没有回答你所询问的实际问题。 - BadHorsie
8个回答

82

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

这绝对有助于我理解这里发生的事情。希望它能够帮到你!

基本上,写成:

arr.filter(Boolean)

等同于写:

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

Boolean()也是一个函数,当参数为true时返回真值(truthy),当参数为false时返回假值(falsy)!

例如:

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

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

来源:这里


61

我遇到类似问题并想出了这个解决方案:

function bouncer(arr) {
  return arr.filter(Boolean);
}
console.log(bouncer([7, 'ate', '', false, 9]));


15

最简单的方法是:

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

15
使用 arr.filter(Boolean) 更简单。 - Nick stands with Ukraine
@NickA 为什么 filter(Boolean) 将 false 判断为 falsy,而 Boolean(false) 却是 truthy? - user25976
1
@user25976,“布尔值”是一个“对象”,所有的对象都可以作为真值来使用,然而,“false”这个“原始类型”的值只是“false”。 - Nick stands with Ukraine
1
你不需要 !!x。只需要 arr.filter(x => x); 就足够了。 - Yonggoo Noh
2
@user25976 Boolean(false) 返回 falsenew Boolean(false) 返回一个对象。关键字 new 使得它们不同。 - Christian Jensen

6

这是因为您返回了一个值。筛选函数应该像这样返回 true 或 false:

function bouncer(arr) {
    arr = arr.filter(function(x) { console.log(x === true)
       if(x !== false) {
           return true;
       }
    });
    return arr;
}

或者更简洁一些:

function bouncer(arr) {
    return arr.filter(function(x) { console.log(x === true)
       return x !== false;
    });
}

3
你的函数之所以能够正常工作,是因为JavaScript中的值在布尔比较时被认为是“真值”或“假值”。非布尔值在布尔上下文中(比较、if语句等)被强制转换为布尔值。
如果我理解你的意图,你可以按照以下方式修改你的函数以获得期望的输出:
function bouncer(arr) {
  // Don't show a false ID to this bouncer.
    function a(b) {
      if(typeof(b) === 'boolean' && !b) {
        return new Boolean(b);
      }
    }

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

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

2

我偶然发现了这个练习,并对它进行了一些尝试。最终帮助我更好地理解了它,所以如果可以的话,我会为这个bouncer函数添加一些清晰度。

function bouncerOne(array){

let truthy = array.filter(x => x);
// This takes the .filter() and applies the anon function where it takes 
// the value and returns the positive value. All values that are not Falsy including 
// objects and functions would return True. 
console.log("The Truth is:", truthy);//this Outputs the result to the console.
let falsy = array.filter(x => !x); 
//This takes the .filer() and applies the 
//annon function where it takes the value and only returns items that ARE NOT True. 
//So Falsy Values are taken. 
console.log("The Falsy Values are",falsy);

//The annon function of (x => x) & (x => !x)
// really makes use of the strict equality power of JavaScript. 
// Where simple conditional test can be carried out.
};
console.log(bouncerOne([7, "ate", "", false, 9,null,42,"Bingo",undefined,NaN]));
//Returns: The Truth is: [ 7, 'ate', 9, 42, 'Bingo' ]
//The Falsy Values are [ '', false, null, undefined, NaN ]

0

基本上,你的if语句在这段代码中没有起到任何作用,因为它没有改变arr,而你将其作为输出返回。如果你设置b!== true或false,它没有任何影响。即使你删除了“if语句”,你也会得到相同的答案。


0

双非运算符(!!)将值转换为布尔形式。 例如:!!true // true;


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

// writing in ES6 syntax
a.filter(v=>!!v); // [1, 2, 'b', {…}, 3, 5]

// writing with function keyword
a.filter( function(v) { return (!!v); }); // [1, 2, 'b', {…}, 3, 5]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接