數(shù)據(jù)類型
js中的基本數(shù)據(jù)類型, 分別為 string, number, boolean, undefined, function, object, symbol 以及未來的 BigInt.
值類型
保存在 棧 中, 每次復(fù)制與賦值操作的都是變量本身的值
const a = 1;
const b = 1;
const c = true;
const d = false;
console.log(a === b); // true
console.log(c === d); // true
注意: 簡單類型 !== 值類型
const a = 1;
const b = new Number(1);
a === b; // ? false
a.length = 2;
b.length = 2;
a.length // ? undefined
b.length // ? 2
// 大坑
const c = new String('');
c.length // ? 0
c.length = 2;
c.length // ? 0
引用類型
保存在堆中, 在賦值等操作實際操作的是對象的內(nèi)存地址.
- 除
function外, 通過typeof不能判斷其準(zhǔn)確類型 - 在操作引用類型是一定注意深拷貝和淺拷貝
- 使用
instanceof和Object.prototype.toString.call來判斷其精確類型
const a = {};
const b = {};
a === b; // false
const a = {test: 1};
const b = a;
b.test = 2;
a.test // 2
// 分析
// eg1
a = {n: 1};
a.x = a = {n: 2}
a.x // ?
// eg2
a = {n: 1};
b = a;
a.x = a = {n: 2}
a.x // ?
b.x // ?