Using quot;Booleanquot; as the argument to .filter() in JavaScript(使用“布尔作为 JavaScript 中 .filter() 的参数)
问题描述
最近了解到可以使用Boolean
关键字来判断一个布尔值是否为false
,例如
Recently I've learned that you can use the Boolean
keyword to check whether a boolean value is false
, e.g.
function countSheeps(arrayOfSheeps) {
return arrayOfSheeps.filter(Boolean).length;
}
arrayOfSheeps
只是一个布尔值数组.由于我一直无法找到有关使用布尔"作为关键字的任何信息,我想知道这个词是否还有其他用途,或者甚至只是我可以用来了解它的任何资源.
Where the arrayOfSheeps
is simply an array of boolean values. As I've been unable to find anything about using 'Boolean' as a keyword, I was wondering if there are any other uses for the word, or even just any resources I can use to learn about it.
推荐答案
Boolean
不是关键字,它是 function,而函数只是对象,可以传递.同理:
Boolean
is not a keyword, it is a function, and functions are just objects, that you can pass around. It is the same as:
return arrayOfSheeps.filter(function(x){return Boolean(x)}).length;
由于 function(x){return f(x)} === f
那么你可以简化:
Since function(x){return f(x)} === f
then you can simplify:
return arrayOfSheeps.filter(Boolean).length;
这篇关于使用“布尔"作为 JavaScript 中 .filter() 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用“布尔"作为 JavaScript 中 .filter() 的参数


基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01