繁体   English   中英

Boolean()函数的意外返回值

[英]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上执行+1NaN ,这是一个值。

...但是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上的对象即属性{}所以它返回undefinedundefined + 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM