[27-1] 強制轉型 - 番外篇 ( 運算子預設的規定 ex: ==、+ )


keywords:implicit coercion,Addition Operator,loose equals

運算子 +

運算子 + 在 number 及 string 之間有著不太一致的行為,在這邊整理一下

  1. 當 + 運算子只有一個運算元的時候,會明確地把運算元強制轉型為一個 number 值,以 number 為主

     +'98';  // 98
    
     +true; // 1
    
     +[2]; // 2
    
     +
    
  2. 當 + 運算子有兩個運算元的時候,以 string 為主
    步驟如下:
    2-1. 將左右參數使用 ToPrimitive 抽象運算取得原生型別值
    2-2. 如果左右參數其中一個型別為 string ,就將雙方都用 ToString 轉成 string 並做字串的連結並回傳
    2-3. 如果左右參數都非 string ,那就一定是 number 的運算
    介紹一個面試遇過的問題:

     1 + 2 + 3 + '4' + 5 + 6; // 6456
    
     步驟 1:
    
     1 + 2 + 3 = 6
    
     步驟 2:
    
     6 + '4'  發現 '4' 為一個 string 所以做字串的連結
    
     = '64'
    
     步驟 3:
    
     '64' + 5  發現 '64' 為一個 string 所以做字串的連結
    
     = '645'
    
     步驟 4:
    
     '645' + 6  發現 '645' 為一個 string 所以做字串的連結
    
     = '6456'
    
  3. 除了 + 之外所有運算子都以 number 為主

     99 - '1'; // 98
    
     '99' / 3; // 33
    
     99 * '0'; // 0
    

寬鬆相等 ( == ),如果左右兩邊型別不同以 number 為主

  1. string vs. number

    '98' == 98; // true
    
  2. boolean vs. any
    boolean 遇到 == 一律都會先轉為 number

     true == 1; // true
    
     true == [1]; // true
    
     =>  1 == '1'
    
     =>  1 == 1
    
     =>  true
    

詳細文章:
[23] 強制轉型 - 明確的強制轉型、Strings <> Numbers、日期轉 Number、位元運算子
[25] 強制轉型 - 隱含的強制轉型、Addition Operator、Strings <> Numbers
[27] 強制轉型 - 寬鬆相等 ( == ) vs. 嚴格相等 ( === )

#implicit coercion #Addition Operator #loose equals







你可能感興趣的文章

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 2

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 2

[#005] 383. Ransom Note

[#005] 383. Ransom Note

Sass 實戰

Sass 實戰






留言討論