Web前端入門第 57 問:JavaScript 數(shù)據(jù)類型與類型轉(zhuǎn)換
在程序語言中,數(shù)據(jù)類型是基礎(chǔ),一切程序都是建立在基礎(chǔ)數(shù)據(jù)之上。
如果說程序如同萬丈高樓平地起,那么數(shù)據(jù)類型就像沙、石、鋼筋、水泥等等最基礎(chǔ)的原料。一樣的高樓,不同的人,用相同的原料,造的方法也會有千般變化。
在 JS 中,數(shù)據(jù)類型可以分為 原始類型 和 對象類型。
原始類型
直接存儲值,不可變(值的地址不可變),共 7 種:
1、number 數(shù)值類型,包括整數(shù)、浮點數(shù)、Infinity、NaN。
const num1 = 123;
const num2 = 123.456;
const num3 = Infinity;
const num4 = NaN;
const num5 = new Number(456); // 使用構(gòu)造函數(shù)聲明,獲得一個 Number 對象
console.log(typeof num5); // object
const num6 = Number(456); // 函數(shù)式聲明 Number 類型
console.log(typeof num6); // number
2、string 字符串類型。單雙引號聲明的字符串不允許換行,可使用反引號申明多行字符串和模版字符串。
const str1 = 'hello'; // JS 中聲明字符串允許單引號和雙引號
const str1_1 = '\'hello\''; // 單引號中還有單引號需要使用反斜線轉(zhuǎn)義字符串
const str2 = " world";
const str3 = str1 + str2; // 字符串拼接,獲得 hello world
const str4 = `前端路引
${str1}${str2}`; // 多行模版字符串聲明,允許有換行和變量存在, ${str1}${str2} 表示拼接兩個變量
const str5 = new String('前端路引');
console.log(typeof str5); // object
const str6 = String('前端路引');
console.log(typeof str6); // number
3、boolean 布爾值(true/false)。
const bool1 = true;
const bool2 = false;
const bool3 = new Boolean(true);
console.log(typeof bool3); // object
const bool4 = Boolean(true);
console.log(typeof bool4); // boolean
4、null 表示空值。
const empty = null;
console.log(typeof empty); // object
5、undefined 未定義的值。
let u1; // 未聲明變量,默認(rèn)為 undefined
const u2 = undefined; // 顯示使用 undefined 聲明變量
6、symbol 唯一且不可變的值(符號)。就算使用 Symbol 聲明的內(nèi)容一樣,但是兩個變量其實是不相等的!!
const sym1 = Symbol('前端路引'); // 帶描述的符號
const sym2 = Symbol('前端路引');
console.log(sym1 === sym2); // false
const sym3 = Symbol.for('前端路引'); // 全局符號
const sym4 = Symbol.for('前端路引');
console.log(sym3 === sym4); // true
console.log(Symbol.keyFor(sym3)); // 前端路引
const sym5 = Symbol(); // 不帶描述的符號
7、bigint 大整數(shù)(以 n 結(jié)尾,如 123n),一般用于表示大于 2^53 - 1 的整數(shù),ES2020+ 引入的新的數(shù)據(jù)類型,使用時需注意兼容性。
const big1 = 123n;
const big2 = BigInt(123);
console.log(big1 === big2); // true
console.log(typeof big1); // bigint
console.log(big1 === 123) // false
console.log(big1 === 123n); // true
對象類型
存儲引用(內(nèi)存地址),可變,包含所有非原始類型的值:
1、普通對象
const obj1 = {}; // 創(chuàng)建一個空對象
const obj2 = { name: '前端路引', age: 1 }; // 帶屬性的對象
const obj3 = new Object(); // 使用構(gòu)造函數(shù)創(chuàng)建對象
const obj4 = Object({name: '前端路引'});
2、數(shù)組
const arr1 = []; // 空數(shù)組
const arr2 = [1, 2, 3]; // 帶元素的數(shù)組
const arr3 = new Array();
const arr4 = Array(10).fill('前端路引'); // 創(chuàng)建一個長度為 10 的數(shù)組,并填充內(nèi)容
3、函數(shù)
function func1() {
console.log('Function 1');
}
const func2 = function() {
console.log('Function 2');
};
const func3 = () => {
console.log('Function 3');
};
除了基礎(chǔ)的三種基礎(chǔ)對象類型外,JS 還內(nèi)置了很多其他對象,比如 Date、RegExp、Error、Map、Set、WeakMap、WeakSet、Promise、Proxy、ArrayBuffer 等。
類型轉(zhuǎn)換
JS 的類型轉(zhuǎn)換分為隱式轉(zhuǎn)換(明確表明由 A 轉(zhuǎn)為 B)和顯式轉(zhuǎn)換(自動發(fā)生的類型轉(zhuǎn)換)。
顯式轉(zhuǎn)換
通過對象方法強制轉(zhuǎn)換:
1、轉(zhuǎn)字符串
String(123); // "123"
[1,2].toString(); // "1,2"
2、轉(zhuǎn)數(shù)字
Number("123"); // 123
Number("abc"); // NaN
parseInt("12px");// 12
3、轉(zhuǎn)布爾
Boolean(""); // false
Boolean({}); // true
隱式轉(zhuǎn)換
一半多發(fā)生于運算符,比如:
1、字符串拼接
console.log('1' + 1); // 11
console.log(1 + '1'); // 11
2、數(shù)學(xué)運算
console.log('1' - 1); // 0
console.log(1 - '1'); // 0
console.log('1' * 1); // 1
console.log(1 * '1'); // 1
console.log('1' / 1); // 1
console.log(1 / '1'); // 1
3、邏輯運算
if (0) { // 0 為 false,將不會執(zhí)行代碼塊
console.log('0');
}
常見轉(zhuǎn)換規(guī)則
| 原始值 | 轉(zhuǎn)字符串 | 轉(zhuǎn)數(shù)字 | 轉(zhuǎn)布爾值 |
|---|---|---|---|
true |
"true" | 1 | true |
false |
"false" | 0 | false |
0 |
"0" | 0 | false |
"" |
"" | 0 | false |
"123" |
"123" | 123 | true |
null |
"null" | 0 | false |
undefined |
"undefined" | NaN | false |
NaN |
"NaN" | NaN | false |
[] |
"" | 0 | true |
[5] |
"5" | 5 | true |
{} |
"[object Object]" | NaN | true |
常見陷阱與最佳實踐
1、== vs ===
==會進(jìn)行類型轉(zhuǎn)換:0 == false為true。===嚴(yán)格比較類型和值,推薦使用。
2、NaN的判斷
NaN === NaN為false,使用Number.isNaN(value)或Object.is(value, NaN)。
3、對象轉(zhuǎn)換
- 對象轉(zhuǎn)原始值時,優(yōu)先調(diào)用
valueOf(),再toString()。 {} + []可能被解析為代碼塊,導(dǎo)致結(jié)果意外。
4、parseInt基數(shù)
- 總是指定基數(shù):
parseInt("08", 10)避免八進(jìn)制誤解。
寫在最后
由于 JavaScript 屬于弱類型語言,所以在編碼時候特別需要注意類型轉(zhuǎn)換問題。特常見問題:后端返回的數(shù)據(jù)類型是字符串 '1',在前端當(dāng)做數(shù)字 1 使用,這時候分分鐘踩雷。
文章首發(fā)于微信公眾號【前端路引】,歡迎 微信掃一掃 查看更多文章。
本文來自博客園,作者:前端路引,轉(zhuǎn)載請注明原文鏈接:http://www.rzrgm.cn/linx/p/18890277

浙公網(wǎng)安備 33010602011771號