js隱式類型轉換


隱式類型轉化

四則運算

  • 加法運算符+是雙目運算符,只要其中一個是String類型,表達式的值便是一個String。
eg:
    var a = 2 + '3'// '23'
  • 對於其他的四則運算,只有其中一個是Number類型,表達式的值便是一個Number。
 eg:
     var a = 3 - '2'// 1
  • 對於非法字符的情況通常會返回NaN:
'1' * 'a'     // => NaN,這是因為parseInt(a)值為NaN,1 * NaN 還是 NaN

判斷語句

  • 判斷語句中的判斷條件需要是Boolean類型,所以條件表達式會被隱式轉換為Boolean。 其轉換規則同Boolean的構造函數。比如:
    var obj = {};
    if(obj){
        dosomething...
    }

JavaScript 原始類型轉換表

原始值 轉化為數值類型 轉化為字符串類型 轉化為 Boolean 類型
false 0 "false" false
true 1 "true" true
0 0 "0" false
1 1 "1" true
"0" 0 "0" true
"1" 1 "1" true
NaN NaN "NaN" false
Infinity Infinity "Infinity" true
-Infinity -Infinity "-Infinity" true
"" 0 "" false
"20" 20 "20" true
"twenty" NaN "twenty" true
[ ] 0 "" true
[20] 20 "20" true
[10,20] NaN "10,20" true
["twenty"] NaN "twenty" true
["ten","twenty"] NaN "ten,twenty" true
function(){} NaN "function(){}" true
{ } NaN "[object Object]" true
null 0 "null" false
undefined NaN "undefined" false


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM