簡體   English   中英

將字符串添加到數字並將數字添加到字符串

[英]Adding strings to numbers and numbers to strings

我在控制台中嘗試了一些不太了解的內容。

如果您添加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. 查找任何符號並將其壓入操作數堆棧:stack:2,2,“ hello”
  3. 從操作員堆棧中獲取第一個操作符,從操作數堆棧中獲取前2個操作數,請執行以下操作:2 + 2 = 4
  4. 取第一個運算符和前兩個操作數,執行:4 +“ hello” =“ 4hello”

請注意,JS自動類型轉換通過+運算符(既是加法又是串聯)以這種方式工作,在其他地方它可能(並且確實)以不同的方式工作。 4 - "hello"將毫無意義,而"0" == true將計算為false,而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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM