使用“布尔”作为JavaScript中.filter()的参数 [英] Using "Boolean" as the argument to .filter() in JavaScript

查看:94
本文介绍了使用“布尔”作为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 只是一个布尔值数组。由于我一直无法找到关于使用'Boolean'作为关键字的任何内容,我想知道该单词是否有任何其他用途,甚至只是我可以用来了解它的任何资源。

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.

推荐答案

布尔值不是关键字,它是 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 然后你可以简化:

return arrayOfSheeps.filter(Boolean).length;

这篇关于使用“布尔”作为JavaScript中.filter()的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆