JavaScript adding a string to a number(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
这篇关于JavaScript 将字符串添加到数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 将字符串添加到数字


- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07