[英]JavaScript: Can the Boolean object be used as a callback function?
I would like to write array.some(Boolean)
as a way to test if any elements in array
are truthy. 我想编写
array.some(Boolean)
作为一种方法来测试array
中的任何元素是否真实。
Are there any issues with using the Boolean
object in this way? 以这种方式使用
Boolean
对象有什么问题吗? Does it have the same behavior across modern browsers? 它在现代浏览器中是否具有相同的行为? Is it always equivalent to
array.some(function(elem) { return !!elem; })
? 它总是等于
array.some(function(elem) { return !!elem; })
?
Are there any issues with using the
Boolean
object in this way?以这种方式使用
Boolean
对象有什么问题吗?
No. Unlike parseInt
for example (which would be problematic), Boolean
only expects a single argument. parseInt
。例如,与parseInt
不同(这会有问题), Boolean
只需要一个参数。 So there shouldn't be any issues with passing the other callback arguments to it (index and the array), it will simply ignore them. 因此,将其他回调参数传递给它(索引和数组)应该没有任何问题,它将简单地忽略它们。
Does it have the same behavior across modern browsers?
它在现代浏览器中是否具有相同的行为?
I do hope so. 我希望如此。 If you can't trust the
Boolean
function, what else is left? 如果您不能信任
Boolean
函数,还剩下什么?
Is it always equivalent to
array.some(function(elem) { return !!elem; })
?它总是等于
array.some(function(elem) { return !!elem; })
?
When
Boolean
is called as a function rather than as a constructor, it performs a type conversion.当
Boolean
作为函数而不是构造函数调用时,它会执行类型转换。
And that's essentially what !!
这基本上是什么
!!
does as well. 也一样。
Relevant references from the spec: 规范中的相关参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.