本文介绍了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() 真正的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)