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];
来源:这里.
相关文章