Why '11' can be converted into the number 11,
but the result of 1 '11' is '111' string?
淡淡烟草味2017-06-12 09:25:43
Since this answer existed before ES6, this answer is taken from ES5.
Answer source: ECMAScript5.1 11.4.6
One dollar +
operation converts its operation value into a number. Don’t ask why, it is defined in the specification.
Answer source: ECMAScript5.1 11.6.1
Steps of addition operation:
Convert the left and right values to metatypes (such as strings and numbers) first; for example, Boolean will be converted to numbers, and objects will usually be converted to strings, etc.;
Add it up
If either the lvalue or rvalue converted value is a string, both values will be converted into strings for splicing operation;
Otherwise, convert both the lvalue and rvalue into numbers, and then perform addition operations on the numbers; (For example, the Boolean conversion element type is not a string, but is still a Boolean, so when judging this branch here, the Boolean Convert to number 1 or 0)
Return results.
阿神2017-06-12 09:25:43
javascript
is a weakly typed language, and that's for one reason. Furthermore, if +
is put together with a number, it is considered a positive number. For example, var a = +11
is equivalent to var a = 11
. In this way, +
will only be used as the concatenation operator when concatenating strings. And + '11'
is not a concatenated string, because there is no concatenated string at all. So js
will implicitly convert '11'
to 11
.
I am also a beginner of js
. This is my understanding. If it is wrong, you are welcome to correct me.
仅有的幸福2017-06-12 09:25:43
+'11' -----> Unary operator
The unary + operator converts its operand to Number type.
1+'11' ----> addition operator
If one of the operands is of string type, convert the other operand to a string and return the result of the concatenation of the two strings.
漂亮男人2017-06-12 09:25:43
The
+ of
+'11'
is the positive of the positive and negative, which is equivalent to Number('11')
1 + '11'
is the addition of addition and subtraction, calling the internal toPrimitive
method for comparison. When one of the parties is a string, it will try to call the other party's toString
method