变量存储类型
- 基本类型:直接存储在栈中的数据。(string、boolean、undefined、number、null)
- 引用类型:将该对象引用地址存储在栈中,然后对象里面的数据存放在堆中。(Array、Object、Function)
浅拷贝
浅拷贝就是指对象复制的时候只复制一层
如何浅拷贝
const person = {
name: '长青',
intoduce: () => {
console.log('你好! 我是长青。')
}
}
// 方法一
const chagnqing1 = Object.assign({}, person)
// 方法二
const chagnqing2 = {...person}
手写浅拷贝
const shallowClone = (target) => {
if (target && typeof target === 'object') {
const temp = Array.isArray(target) ? [] : {}
for (let key in target) {
temp[key] = target[key]
}
return temp
}
return target
}
深拷贝
深拷贝是指复制对象的所有层级
如何深拷贝
const person = {
name: '长青',
info:{},
intoduce: () => {
console.log('你好! 我是长青。')
}
}
// =====================方法一==================================
// 乞丐版(JSON.stringify)会存在属性丢失
let cq = JSON.parse(JSON.stringify(person))
// =====================方法二==================================
// 使用递归进行深拷贝
const deepClone = (target, hash = new WeakMap()) => {
if (target.constructor === Date)
return new Date(target) // 日期对象直接返回一个新的日期对象
if (target.constructor === RegExp)
return new RegExp(target)
// 引入 hash 解决循环引用
if (hash.has(target)) return hash.get(target)
hash.set(target, target)
if (target && typeof target === 'object') {
const temp = Array.isArray(target) ? [] : {}
for (let key in target) {
if (typeof target[key] === 'object') {
temp[key] = deepClone(target[key], hash)
} else {
temp[key] = target[key]
}
}
return temp
}
return target
}
const lmm = deepClone(person)
lmm.name = '林妹妹'
lmm.info.gender = false
console.log(lmm);
console.log(person);