JavaScript adding a string to a number
I was reading the re-introduction to JavaScript on MDN and in the section Numbers it said that you can convert a string to a number simply by adding a plus operator in front of it.
For example:
+"42" which would yield the number output of 42.
But further along in the section about Operators it says that by adding a string "something" to any number you can convert that number to a string. They also provide the following example which confused me:
"3" + 4 + 5 would presumably yield a string of 345 in the output, because numbers 4 and 5 would also be converted to strings.
However, wouldn't 3 + 4 + "5" yield a number of 12 instead of a string 75 as was stated in their example?
In this second example in the section about operators wouldn't the + operator which is standing in front of a string "5" convert that string into number 5 and then add everything up to equal 12?
What you are talking about is a unary plus. It is different than the plus that is used with string concatenation or addition.
If you want to use a unary plus to convert and have it added to the previous value, you need to double up on it.
> 3 + 4 + "5"
"75"
> 3 + 4 + +"5"
12
Edit:
You need to learn about order of operations:
+
and -
have the same precedence and are associated to the left:
> 4 - 3 + 5
(4 - 3) + 5
1 + 5
6
+
associating to the left again:
> 3 + 4 + "5"
(3 + 4) + "5"
7 + "5"
75
unary operators normally have stronger precedence than binary operators:
> 3 + 4 + +"5"
(3 + 4) + (+"5")
7 + (+"5")
7 + 5
12
You could also use parseInt() or parseFloat(), like this:
> 1 + 2 + "3"
"33"
> 1 + 2 + parseInt(3)
6
I think that's alot cleaner than using +"3", but that is just my opinion.
The answer can be found in Ecma262.pdf section 11.6.1:
If Type(lprim) is String or Type(rprim) is String, then a. Return the String that is the result of concatenating ToString( lprim) followed by ToString(rprim).
So that will resolve all operations according to precedence, so that as soon the string is found any number, the number is converted to string.
4 + 3 + "5"
"75"
4 + 3 + "5" + 3
"753"
To read the whole standard, go here.
链接地址: http://www.djcxy.com/p/73940.html上一篇: 如何从输入元素中获取值作为十进制数字