将字符串添加到数字,将数字添加到字符串

Adding strings to numbers and numbers to strings

本文关键字:数字 添加 字符串      更新时间:2023-09-26

我在控制台中尝试了一些我不太理解的东西。

如果添加 2 + 3 + "hello",它将连接到"5hello">

但是,如果您保留此内容并添加"hello"+ 2 + 3,它将连接到"hello23">

为什么?我的猜测是因为 JavaScript 查看第一个数据类型并尝试将其转换为该类型?有人可以详细说明一下吗?

加法(和其他关联运算符(按从左到右的顺序进行处理。所以

2 + 3 + "hello"

就像写作

(2 + 3) + "hello"

5 + "hello"

首先是加法,然后是转换/串联。另一方面

"hello" + 2 + 3

就像:

("hello" + 2) + 3

这适用于

"hello2" + 3

"hello23"

操作顺序很简单:

2 + 2 + "hello" //2 + 2 is evaluated first, resulting in 4. 4 + "hello" results in "4hello";
"hello" + 2 + 3 //"hello" + 2 is evaluated first, turning the result to a string, and then "hello2" + 3 is done.

据我了解,2 + 2 + "hello"是这样评估的:

  1. 找到任何运算符并将它们推送到运算符堆栈上:堆栈:+、+
  2. 找到任何符号并将它们推送到操作数堆栈上:堆栈:2,2,"hello">
  3. 从运算符堆栈中获取第一个运算符,然后操作数堆栈中的前 2 个操作数,do:2 + 2 = 4
  4. 取第一个运算符和前 2 个操作数,做:4 + "hello"= "4hello">

请注意,JS自动类型转换以这种方式与+运算符(既是加法又是连接(一起工作,它可能(并且确实(在其他地方的工作方式不同。 4 - "hello"将毫无意义,"0" == true将评估为错误,而0 == ''站得住脚。这就是Javascript成为当今最受欢迎的语言之一的原因之一。

这是由于强制而发生的。类型强制意味着当一个运算符的操作数是不同类型的操作数时,其中一个操作数将被转换为另一个操作数类型的"等效"值。要考虑的操作数取决于"数据类型"的层次结构(尽管 JavaScript 是无类型的(,并且操作从左到右执行。例如:

//from left to right
2 + 3 + "hello"
//performs the addition, then does coercion to "string" and concatenates the text
(2 + 3) + "hello"

这会导致"5hello"

在对应方

//from left to right
'hello' + 2 + 3
//string concatenation is the first, all subsequent values will do coercion to string
"hello23"

除非您使用括号,否则其优先级更高

'hello' + (2 + 3)

它返回"hello5"