2014-10-30 222 views
0

我在我的控制台中尝试了一些我不太明白的东西。将字符串添加到字符串的数字和数字

如果添加2 + 3 + “你好” 它加到 “5hello”

但是,如果保留这一点,并添加 '你好' + 2 + 3它加到 'hello23'

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

+0

“+”运算符是从左到右的关联:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence。 – 2014-10-30 20:07:29

回答

1

加法(和其他关联运营商)的顺序进行处理,左到右。所以

2 + 3 + "hello" 

是这样写

(2 + 3) + "hello" 

5 + "hello" 

第一加法,那么转换/级联。在另一方面,

"hello" + 2 + 3 

是这样的:

("hello" + 2) + 3 

该工程以

"hello2" + 3 

"hello23" 
0

简单为了真正做到:

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. 
0

据我了解,2 + 2 + "hello"评价此方式:

  1. 找到任何运营商,推动它们的运算符堆栈:堆栈:+,+
  2. 查找任何符号,把他们的操作数堆栈:堆栈:2,2,“你好”
  3. 拿从操作者堆叠第一运营商和 从操作数的第一2个操作数堆栈,做到:2 + 2 = 4
  4. 采取第一操作者和所述第一2个操作数,执行:4 +“你好” =“4hello”

介意你, JS自动类型转换以+运算符(既是加法又是连接)这种方式工作,它可能(并且确实)在其他地方以不同的方式工作。 4 - "hello"将毫无意义,"0" == true将评估为false,而0 == ''的立场。这是Javascript是今天最受欢迎的语言之一。

0

这是由于强制。类型强制意味着当一个操作符的操作数是不同类型时,其中一个将被转换为另一个操作数类型的“等效”值。要考虑的操作数取决于“数据类型”的层次结构(尽管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"