问题描述
我在做一些测试转换值在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
这给我转换如何进行更好的主意。 Acording此表
[] => 0
[20] => 20
[10,20] =>为NaN
[廿] =>南
[十,二] =>为NaN
所以aparently他们采取数组的第一个值,并使用指定的规则进行转换。 parseInt函数的规则并不适用。
我测试得出这一结论。您可以嵌套的这一切你想要的,它会给你同样的结果。
的console.log(+ [[[[[[[[[[[10]]]]]]]]]]])=> 10
于是我就想,好吧,如果是这样的话
的console.log(+ [未定义])将返回NaN的
的console.log(+ [空])将返回0
的console.log(+ [虚假])将返回0
这些都是从JavaScript的转换表预计整数值,但原来
的console.log(+ [未定义)=> 0
的console.log(+ [空])=> 0
的console.log(+ [虚假])=>为NaN
最后一个是最奇怪的,因为假转换为0,而不是为NaN。
有人可以解释的奇怪行为或解释如何进行这种转换?
的的内部使用的 ToNumber 的抽象操作。
的 ToNumber 的抽象操作一>,当应用于对象,通过的),然后再应用的 ToNumber 的上生成的字符串重新presentation操作。
在这里有趣的是Array的的toString
方法。需要注意的是 [虚假]的ToString()
是不可同日而语[未定义]的ToString()
或 [空]的ToString()
。当我们检查了,我们看到,在内部它使用的。步骤8 加入
算法说道:
Thus, any array containing a single null
or undefined
stringifies to the empty string (which ToNumber number-ifies to 0
), while other values will stringify to some other string (which will then number-ify to NaN
if the string is non-numeric).
+[undefined]
is the same as +""
, while +[false]
is the same as +"false"
.
这篇关于为什么使用一元运算符+阵列上提供的JavaScript不一致的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!