[英]unexpected return value of Boolean() function
为了确定对象是数组还是对象列表,我提出了这种方法:
var foo = {}
Boolean(foo["length"]+1) // returns false because foo is an object
var foo = []
Boolean(foo["length"]+1) // returns true because foo is an array
然而,在看了这个之后,我意识到它应该不起作用。 []["length"]+1
显然是真的,因为它等于1. {}["length"]+1
等于"length1"
,这也是真的,因为它没有未定义。
那么为什么Boolean({}["length"]+1)
返回false但Boolean("length1")
返回true?
那么为什么
Boolean({}["length"]+1)
返回false ...
因为对象没有length
属性,所以{}["length"]
将返回undefined
并且尝试在undefined
上执行+1
是NaN
,这是一个假值。
...但是
Boolean("length1")
返回true?
因为字符串length1
是真值。
更好的测试是查看有问题的项目是否只有一个属性/方法。 这称为“特征检测” ,在JavaScript中广泛使用
let obj1 = {}; let obj2 = []; console.log(obj1.length); // undefined: objects don't have length console.log(obj1.hasOwnProperty); // native function (ie. truthy) console.log(obj2.length); // 0: Arrays have length and this one's is 0 console.log(obj2.map); // the native function (ie. truthy)
Boolean({}["length"]+1)
返回false
,因为没有length
上的对象即属性{}
所以它返回undefined
和undefined + 1
返回NaN
这是falsy值
Boolean({}["length"]+1)
Boolean(undefined+1)
Boolean(NaN)
false
Boolean("length1")
返回true,因为"length1"
length1 "length1"
是字符串和trucy值。 注意除了空字符串""
之外,所有字符串都是trucy
强制转换为Boolean
时,以下值将始终返回false
,而其他值将返回true
console.log(Boolean(0)); console.log(Boolean('')); console.log(Boolean(null)); console.log(Boolean(undefined)); console.log(Boolean(false)); console.log(Boolean(NaN));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.