一、基本類型轉換
1、數字轉字符串
let num = 3; let str = num.toString(); console.log(typeof str); // string
2、字符串轉數字
let str = "3"; let num = Number(str); console.log(typeof num); // number
3、布爾值轉換為數字
let bool = true; let num = Number(bool); // 1 bool = false; num = Number(bool); // 0
4、數字轉布爾值
let num = 0; let bool = Boolean(num); // false num = 1; bool = Boolean(num); // true
二、對象類型轉換
1、對象轉字符串
let obj = {key: "value"}; let str = JSON.stringify(obj); console.log(typeof str); // string
2、字符串轉對象
let str = '{"key": "value"}'; let obj = JSON.parse(str); console.log(typeof obj); // object
3、對象轉數字
let obj = {key: "value"}; let num = Number(obj); // NaN
4、數字轉對象
let num = 123; let obj = Object(num); console.log(obj); // Number {123}
三、隱式類型轉換
1、數字與字符串拼接
let num = 1; let str = "2"; let newStr = num + str; console.log(typeof newStr); // string
2、布爾值作為數字使用
let bool = true; let num = bool + 1; console.log(num); // 2
3、null、undefined轉換
let num = null; console.log(typeof num); // object let num2; console.log(num2); // undefined let num3 = num2 + 1; console.log(num3); // NaN
四、顯示類型轉換
1、字符串轉數字
let str = "3"; let num = parseInt(str); console.log(typeof num); // number str = "3.5"; num = parseFloat(str); console.log(num); // 3.5
2、數字轉字符串
let num = 3; let str = num.toString(); console.log(typeof str); // string
3、強制轉換
let num = 3; let str = String(num); console.log(typeof str); // string num = Number(str); console.log(typeof num); // number
五、總結
JavaScript的類型轉換非常靈活,並且存在很多“坑”,需要我們謹慎使用。在日常開發中,如果出現類型轉換的情況,需要注意上述細節,以避免由此產生的問題。
原創文章,作者:KRJNL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/371594.html