JavaScript将字符串添加到数字中

编程入门 行业动态 更新时间:2024-10-28 04:17:49
本文介绍了JavaScript将字符串添加到数字中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

例如:

+42这将产生42的数字输出。

但是进一步在关于 Operators 的部分中,它表示通过向任何数字添加字符串something,您可以将该数字转换为字符串。他们还提供了以下让我困惑的例子:

3+ 4 + 5可能会在输出中产生345的字符串,因为数字4和5也会转换为字符串。

然而,3 + 4 +5不会产生12的数字而不是字符串75,如他们的例子中所述? / p>

在关于运算符的部分的第二个例子中,站在字符串5前面的+运算符不会将该字符串转换为数字5,然后添加所有内容最多等于12?

解决方案

你所说的是一元加号。它与字符串连接或添加使用的加号不同。

如果要使用一元加号进行转换并将其添加到之前的值,需要加倍努力。

> 3 + 4 +575> 3 + 4 + +5 12

编辑:

您需要了解操作顺序:

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

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

+ 再次与左边相关:

> 3 + 4 +5(3 + 4)+5 7 +5 75

一元运算符通常比二元运算符具有更强的优先级:

> 3 + 4 + +5(3 + 4)+(+5) 7 +(+5) 7 + 5 12

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

更多推荐

JavaScript将字符串添加到数字中

本文发布于:2023-10-12 17:42:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!