-
浅拷贝
Object.assign 只会拷贝所有的属性值到新的对象中,如果属性值是对象的话,拷贝的是地址,所以并不是深拷贝let a = { age: 1 } let b = Object.assign({}, a) a.age = 2 console.log(b.age) // 1
let a = { age: 1 } let b = { ...a } a.age = 2 console.log(b.age) // 1
-
深拷贝
-
1、JSON转换
let res = JSON.parse(JSON.stringify(copyObj)) let arr2 = JSON.parse(JSON.stringify(arr))
缺点:
- 无法拷贝undefined、symbol、function、RegExp,不能解决循环引用对象
- 无法拷贝copyObj对象原型链上的属性和方法
- 当数据层次很深,会栈溢出
-
2、递归拷贝
function deepClone(source){ if (!isObject(source)) return source for (let k in source){ if (typeof source[k] === 'object'){ target[k] = deepClone(source[k]) }else{ target[k] = source[k] } } } function isObject(obj){ return typeof obj === 'object' && obj !== null }
// 防止对象层数太深栈溢出 function deepClone(source){ if (!isObject(source)) return source const root = {} const loop = [{parent: root, key: undefined, data: source}] while(loop.length){ const node = loop.pop() const parent = node.parent const key = node.key const data = node.data let res = parent if (typeof key !== 'undefined'){ res = parent[key] = {} } for(let k in data){ if (data.hasOwnProperty(k)){ if (typeof data[k] === 'object'){ loop.push({parent: res, key: k, data: data[k]}) }else{ res[k] = data[k] } } } } return root }
-
JS深浅拷贝
最新推荐文章于 2024-08-04 16:33:59 发布