JavaScript 将字符串添加到数字

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)