Why using the unary operator + on an array gives inconsistent results in javascript?

前端 未结 1 576
Happy的楠姐
Happy的楠姐 2020-12-19 02:34

I was doing some testing converting values to integer in javascript and printing the output in the console when I came across with this strange behavior.

con         


        
相关标签:
1条回答
  • 2020-12-19 03:02

    The Unary + operator internally uses the ToNumber abstract operation.

    The ToNumber abstract operation, when applied to objects, calls the object's toString method (by way of the [[DefaultValue]] internal method) and then re-applies the ToNumber operation on the resulting string representation.

    The interesting thing here is Array's toString method. Note that [false].toString() is quite different from [undefined].toString() or [null].toString(). When we inspect the specification for Array.prototype.toString, we see that internally it uses Array.prototype.join. Step 8 of the join algorithm says:

    1. If element0 is undefined or null, let R be the empty String; otherwise, Let R be ToString(element0).

    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".

    0 讨论(0)
提交回复
热议问题