我们先来看几个题目
- typeof能判断哪些类型
- 何时使用=== 何时使用==
- 值类型和引用类型的区别
- 手写深拷贝
知识点


- 值类型 vs引用类型
栈是一个存储变量的地方
值类型:比较小,可以直接存在栈中;
undefined,null,string,number,boolean,symbol
(null比较特殊,笔者认为它是一个原始数据类型,但它的指针指向空地址,js把机械码标签为0的都定义为object,null是0x000,所以也被误认为object)
引用类型:有的很大,所以会把引用地址存在栈中,而实际的值在堆中;
对象,数组,函数(函数:不用于存储数据,所以没有拷贝复制函数这一说,函数内是可执行代码)

- typeof运算符
- 识别所有的值类型除了null
- 识别函数(function)
- 判断是否是引用类型(不能识别引用类型以及null)
typeof null => 'object'
typeof [] => 'object'
typeof {x:1} => 'object'
- 深拷贝(主要是递归)
除了手写外,可以自己画一下深拷贝存储值到的过程
const obj1 = {
age: 20,
name: 'xxx',
address: {
city: 'beijing'
},
arr: ['a', 'b', 'c']
}
const obj2 = deepClone(obj1)
obj2.address.city = 'shanghai'
obj2.arr[0] = 'a1'
console.log(obj1.address.city)
console.log(obj1.arr[0])
function deepClone(obj = {}) {
if (typeof obj !== 'object' || obj == null) {
return obj
}
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key])
}
}
return result
}