Why Does 2..tostring() Work?
Solution 1:
That's because 2.
is parsed as 2.0
, so 2..toString()
is equivalent to 2.0.toString()
, which is a valid expression.
On the other hand, 2.toString()
is parsed as 2.0toString()
, which is a syntax error.
Solution 2:
2
is just a number, it doesn't have any methods to call.
2.
can be coerced into a string, which is an object (i.e. '2.0'
), hence can have the method.
Just 2.toString()
will be parsed as 2.0tostring()
, which of course doesn't make sense.
Looking at how the two are parsed:
vs
The tool to generate these is here by the way: http://jsparse.meteor.com/
Solution 3:
2.toString()
The interpreter sees 2
and thinks, "oh, a number!" Then, it sees the dot and thinks, "oh, a decimal number!" And then, it goes to the next character and sees a t
, and it gets confused. "2.t
is not a valid decimal number," it says, as it throws a syntax error.
2..toString()
The interpreter sees 2
and thinks, "oh, a number!" Then, it sees the dot and thinks, "oh, a decimal number!" Then, it sees another dot and thinks, "oh, I guess that was the end of our number. Now, we're looking at the properties of this object (the number 2.0)." Then, it calls the toString
method of the 2.0
object.
Solution 4:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString
As the Number object overrides the toString method of the Object object, you first have to explicity use paranthesis to indicate that it is a number, and not an object.
My guess is that 2.
implicitly defines it as a float, which is then able to use the .toString()
method of the Number object, and not the method of the Object object.
Solution 5:
2..toString()
will be interpreted as 2.0.toString()
.
Actually, 2.
is a number: console.log(typeof 2.);
will be give: number
Post a Comment for "Why Does 2..tostring() Work?"