添加String with Integer如何在JavaScript中工作? [英] How does adding String with Integer work in JavaScript?

查看:101
本文介绍了添加String with Integer如何在JavaScript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码给出了奇怪的结果:

The following code gives weird results:

console.log("" + 1 + 10 + 2 - 5 + "8");

我已经尝试输入各种不同的值来解决它但我无法理解幕后发生的事情。

I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.

推荐答案

"" + 1          === "1"
"1" + 10        === "110"
"110" + 2       === "1102"
"1102" - 5      === 1097
1097 + "8"      === "10978"

在JavaScript中, + 运算符用于数字加法和字符串连接。当您向字符串添加数字时,解释器会将您的数字转换为字符串并将它们连接在一起。

In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.

当您使用 - 运算符,然而,字符串被转换回数字,以便可能发生数字减法。

When you use the - operator, however, the string is converted back into a number so that numeric subtraction may occur.

当你然后添加一个字符串8,再次发生字符串连接。数字 1097 被转换为字符串1097,然后加入8

When you then "add" a string "8", string concatenation occurs again. The number 1097 is converted into the string "1097", and then joined with "8".

这篇关于添加String with Integer如何在JavaScript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆