javascript
Web前端入门第 57 问:JavaScript 数据类型与类型转换
在程序語言中,數(shù)據(jù)類型是基礎(chǔ),一切程序都是建立在基礎(chǔ)數(shù)據(jù)之上。
如果說程序如同萬丈高樓平地起,那么數(shù)據(jù)類型就像沙、石、鋼筋、水泥等等最基礎(chǔ)的原料。一樣的高樓,不同的人,用相同的原料,造的方法也會(huì)有千般變化。
在 JS 中,數(shù)據(jù)類型可以分為 原始類型 和 對(duì)象類型。
原始類型
直接存儲(chǔ)值,不可變(值的地址不可變),共 7 種:
1、number 數(shù)值類型,包括整數(shù)、浮點(diǎn)數(shù)、Infinity、NaN。
const num1 = 123;
const num2 = 123.456;
const num3 = Infinity;
const num4 = NaN;
const num5 = new Number(456); // 使用構(gòu)造函數(shù)聲明,獲得一個(gè) Number 對(duì)象
console.log(typeof num5); // object
const num6 = Number(456); // 函數(shù)式聲明 Number 類型
console.log(typeof num6); // number
2、string 字符串類型。單雙引號(hào)聲明的字符串不允許換行,可使用反引號(hào)申明多行字符串和模版字符串。
const str1 = 'hello'; // JS 中聲明字符串允許單引號(hào)和雙引號(hào)
const str1_1 = '\'hello\''; // 單引號(hào)中還有單引號(hào)需要使用反斜線轉(zhuǎn)義字符串
const str2 = " world";
const str3 = str1 + str2; // 字符串拼接,獲得 hello world
const str4 = `前端路引
${str1}${str2}`; // 多行模版字符串聲明,允許有換行和變量存在, ${str1}${str2} 表示拼接兩個(gè)變量
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 唯一且不可變的值(符號(hào))。就算使用 Symbol 聲明的內(nèi)容一樣,但是兩個(gè)變量其實(shí)是不相等的!!
const sym1 = Symbol('前端路引'); // 帶描述的符號(hào)
const sym2 = Symbol('前端路引');
console.log(sym1 === sym2); // false
const sym3 = Symbol.for('前端路引'); // 全局符號(hào)
const sym4 = Symbol.for('前端路引');
console.log(sym3 === sym4); // true
console.log(Symbol.keyFor(sym3)); // 前端路引
const sym5 = Symbol(); // 不帶描述的符號(hào)
7、bigint 大整數(shù)(以 n 結(jié)尾,如 123n),一般用于表示大于 2^53 - 1 的整數(shù),ES2020+ 引入的新的數(shù)據(jù)類型,使用時(shí)需注意兼容性。
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
對(duì)象類型
存儲(chǔ)引用(內(nèi)存地址),可變,包含所有非原始類型的值:
1、普通對(duì)象
const obj1 = {}; // 創(chuàng)建一個(gè)空對(duì)象
const obj2 = { name: '前端路引', age: 1 }; // 帶屬性的對(duì)象
const obj3 = new Object(); // 使用構(gòu)造函數(shù)創(chuàng)建對(duì)象
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)建一個(gè)長度為 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ǔ)對(duì)象類型外,JS 還內(nèi)置了很多其他對(duì)象,比如 Date、RegExp、Error、Map、Set、WeakMap、WeakSet、Promise、Proxy、ArrayBuffer 等。
類型轉(zhuǎn)換
JS 的類型轉(zhuǎn)換分為隱式轉(zhuǎn)換(明確表明由 A 轉(zhuǎn)為 B)和顯式轉(zhuǎn)換(自動(dòng)發(fā)生的類型轉(zhuǎn)換)。
顯式轉(zhuǎn)換
通過對(duì)象方法強(qiáng)制轉(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ā)生于運(yùn)算符,比如:
1、字符串拼接
console.log('1' + 1); // 11
console.log(1 + '1'); // 11
2、數(shù)學(xué)運(yùn)算
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、邏輯運(yùn)算
if (0) { // 0 為 false,將不會(huì)執(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 |
常見陷阱與最佳實(shí)踐
1、== vs ===
==會(huì)進(jìn)行類型轉(zhuǎn)換:0 == false為true。===嚴(yán)格比較類型和值,推薦使用。
2、NaN的判斷
NaN === NaN為false,使用Number.isNaN(value)或Object.is(value, NaN)。
3、對(duì)象轉(zhuǎn)換
- 對(duì)象轉(zhuǎn)原始值時(shí),優(yōu)先調(diào)用
valueOf(),再toString()。 {} + []可能被解析為代碼塊,導(dǎo)致結(jié)果意外。
4、parseInt基數(shù)
- 總是指定基數(shù):
parseInt("08", 10)避免八進(jìn)制誤解。
寫在最后
由于 JavaScript 屬于弱類型語言,所以在編碼時(shí)候特別需要注意類型轉(zhuǎn)換問題。特常見問題:后端返回的數(shù)據(jù)類型是字符串 '1',在前端當(dāng)做數(shù)字 1 使用,這時(shí)候分分鐘踩雷。
總結(jié)
以上是生活随笔為你收集整理的Web前端入门第 57 问:JavaScript 数据类型与类型转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hystrix 服务的隔离策略对比,信号
- 下一篇: C# 文件系统