值和引用
数据类型
- 值(基础)类型:
string
、number
、boolean
、null
、undefined
、symbol
、bigint
- 引用类型:
object
、array
、function
值(基础)类型
js
const a = 1;
const bol = true;
const str = "hello";
const n = null;
const u = undefined;
const s = Symbol("symbol");
const b = BigInt(1);
console.log(typeof a); // number
console.log(typeof bol); // boolean
console.log(typeof str); // string
console.log(typeof n); // object
console.log(typeof u); // undefined
console.log(typeof s); // symbol
console.log(typeof b); // bigint
TIP
typeof
可以用来判断值的类型typeof
对于null
返回object
,这是 JavaScript 的一个历史遗留问题,需要特别注意- 具体原因是因为不同的对象在底层都是以二进制存储,在 JavaScript 中,前三位都为 0 会被判断为 object 类型,而
null
的二进制表示全为 0,所以 typeof null 会返回object
null
null
表示空对象指针,转为数值为 0 经典用法:
- 作为函数的参数,表示该函数的参数不是对象
- 作为对象原型链的终点
undefined
undefined
表示未定义,转为数值为 NaN 经典用法:
- 变量未初始化
- 函数无返回值
- 对象属性不存在
- 函数参数未传递
引用类型
- 引用类型:
object
、array
、function
- 引用类型存在堆内存中,栈内存中存储的是引用类型的地址
比较
- 值类型比较的是值
- 引用类型比较的是地址
赋值
- 值类型赋值是
值
的复制 - 引用类型赋值是
地址
的复制
访问
- 值类型访问的是
值
- 引用类型访问的是
地址
动态属性
- 值类型不能动态添加属性
- 引用类型可以动态添加属性