javascript .filter() true booleans(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() 真正的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javascript .filter() 真正的布尔值


- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07