基本类型 & 引用类型
- 基本类型:undefined,null,Boolean,String,Number,Symbol,BigInt
- 引用类型:Object,Array,Date,Function,RegExp等 基本类型固定大小,保存在栈中; 引用类型的值是对象,保存在堆中,在栈内存中保存着引用类型在栈中的地址
深浅拷贝
浅拷贝:复制的引用类型只复制了地址,彼此间对数据的操作会互相影响 深拷贝:在堆中开辟一个新的空间,在栈中存放新空间的地址,这样新的值与原始值就不会互相影响
总的来说,深浅拷贝的主要区别就是:复制的是引用还是复制的是实例
手写深拷贝函数
来看看一行代码版本
JSON.parse(JSON.stringify(obj))
直观代码
function deepClone (obj) {
if (typeof obj !== 'object' || obj == null) {
// obj是null,或者不是对象和数组,直接返回
return obj
}
// 初始化返回结果
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
for (let key in obj) {
// 保证key不是原型属性
if (obj.hasOwnProperty(key)) {
// 递归调用!!! 主要是为了防止有嵌套对象
result[key] = deepClone(obj[key])
}
}
// 返回结果
return result
}
}
简写代码
function deepCopy(obj) {
let result = obj instanceof Array ? [] : {}
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
result[i] = obj[i] instanceof Object ? deepCopy(obj[i]) : obj[i]
}
}
return result;
}