See the code below:
2.toString(); // error
2..toString(); // "2"
2...toString(); // error
I want to know why 2..toString()
can run without errors and what happens when it runs?
Can somebody explain it?
The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.
toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.
If the hint is String , then toString is used before valueOf . But, if the hint is Number , then valueOf will be used first. Note that if only one is present, or it returns a non-primitive, it will usually call the other as the second choice.
toString(2) converts to binary, the tilde ( ~ ) is a bitwise unary operator stackoverflow.com/questions/791328/…
http://shamansir.github.io/JavaScript-Garden/en/#object
A common misconception is that number literals cannot be used as objects. That is because a flaw in JavaScript's parser tries to parse the dot notation on a number as a floating point literal.
2.toString(); // raises SyntaxError
There are a couple of workarounds that can be used to make number literals act as objects too.
2..toString(); // the second point is correctly recognized 2 .toString(); // note the space left to the dot (2).toString(); // 2 is evaluated first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With