Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...