JavaScript 在進行運算時,經常會自動將變數轉型。這一節整理常見隱性轉型的規則
規則一:前後運算元如果其中之一為 “字串” 型別,+ 視為字串運算子
// 結果:'1true'
console.log('1' + true);
規則二:前後運算元如果無法轉型為原始型別(就是指物件型別),+ 視為字串運算子
//[]會被轉換成空字串
console.log(1 + [])
//{} 單獨轉換時結果是 '[object Object]'
console.log(String([]))
//{} 轉成 '[object Object]'
console.log(1 + {})
//{a:1} 轉成 '[object Object]'
console.log(1 + {a:1})
規則三:上述情況以外,+ 視為算數運算子
// true 轉成 1,1 + 1 = 2
console.log(1 + true);
一律套用 Number 轉型,ex:true會被轉型成1
//100
console.log(true * 100)
//-99
console.log(true - 100)
陣列轉字串再轉數字
// [100,10] -> '100,10' -> Number('100,10') = NaN
console.log([100,10] * 100); // NaN
Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
未捕獲的類型錯誤:無法混合 BigInt 和其他類型,請使用明確轉換
console.log(1 + 1n)
Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
未捕獲的類型錯誤:無法混合 BigInt 和其他類型,請使用明確轉換
console.log(1n * 1);
JavaScript 不允許隱式地將 Symbol
類型的值轉換為數字或字串進行加法運算
Uncaught TypeError: Cannot convert a Symbol value to a number
console.log(1 + Symbol(1));
Uncaught TypeError: Cannot convert a Symbol value to a string
console.log({} + Symbol(1));