当我遇到这种奇怪的行为时,我正在做一些测试,将javascript中的值转换为整数,并在控制台中打印输出。
console.log(+[]) ==> 0
console.log(+[123]) ==> 123
console.log(+['123']) ==> 123
console.log(+[123, 456]) ==> NaN
console.log(+['123asdf']) ==> NaN
我以为使用parseInt转换了值,但事实并非如此,所以我去了javascript转换表http://www.w3schools.com/js/js_type_conversion.asp
这使我对如何执行转换有了更好的了解。根据此表
[] => 0
[20] => 20
[10,20] => NaN
["twenty"] =>NaN
["ten","twenty"] => NaN
因此,显然,它们采用数组的第一个值,并使用指定的规则对其进行转换。parseInt的规则不适用。
我测试得出了这个结论。您可以嵌套所有想要的内容,它将获得相同的结果。
console.log(+[[[[[[[[[[[10]]]]]]]]]]]) => 10
所以我想,如果是这样的话
console.log(+[undefined]) will return NaN
console.log(+[null]) will return 0
console.log(+[false]) will return 0
这些是从javascript转换表转换为整数所需的值,但结果是
console.log(+[undefined]) => 0
console.log(+[null]) => 0
console.log(+[false]) => NaN
最后一个是最奇怪的,因为false转换为0,而不是NaN。有人可以解释奇怪的行为或解释如何执行此转换吗?
在一元+运营商内部使用ToNumber抽象操作。
所述ToNumber抽象操作,当施加到对象,调用该对象的toString
方法(由的方式[[DefaultValue]]
内部方法),然后再施加ToNumber对所得字符串表示的操作。
有趣的是Array的toString
方法。请注意,这[false].toString()
与[undefined].toString()
或完全不同[null].toString()
。当我们检查规范时Array.prototype.toString
,我们发现它在内部使用Array.prototype.join
。该join
算法的步骤8说:
- 如果element0是
undefined
或null
,则让R为空String;否则为0。否则,令R为ToString(element0)。
因此,任何包含单个null
或undefined
字符串的数组都将字符串化为空字符串(ToNumber将其数字化为0
),而其他值将字符串化为其他字符串(NaN
如果字符串为非数字则将其数字化为)。
+[undefined]
与相同+""
,而+[false]
与相同+"false"
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句