JavaScript 将字符串添加到数字

2022-01-17 00:00:00 string numbers operators javascript

我正在阅读 在 MDN 上重新介绍 JavaScript 并且在 Numbers 部分中它说您可以通过在字符串前面添加一个加号运算符来将字符串转换为数字.

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.

例如:

+"42" 这将产生 42 的数字输出.

+"42" which would yield the number output of 42.

但是在关于 Operators 的部分中,它说通过将字符串某物"添加到任何数字,您可以将该数字转换为字符串.他们还提供了以下让我感到困惑的示例:

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 大概会在输出中产生一个 345 的字符串,因为数字 4 和 5 也会被转换为字符串.

"3" + 4 + 5 would presumably yield a string of 345 in the output, because numbers 4 and 5 would also be converted to strings.

但是,3 + 4 + "5" 不会产生数字 12 而不是他们示例中所述的字符串 75?

However, wouldn't 3 + 4 + "5" yield a number of 12 instead of a string 75 as was stated in their example?

在关于运算符部分的第二个示例中,位于字符串5"前面的 + 运算符不会将该字符串转换为数字 5,然后将所有内容相加到等于 12 吗?

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

您需要了解操作顺序:

+- 具有相同的优先级并关联到左侧:

+ and - have the same precedence and are associated to the left:

 > 4 - 3 + 5
 (4 - 3) + 5
 1 + 5
 6

+ 再次向左关联:

> 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

相关文章