2014-10-30 234 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"