JSON 拷貝
let result = JSON.parse(JSON.stringify(obj)) 深拷貝
Object.assign()
可枚舉的數(shù)據(jù)
const obj = {}
const obj1 = { name: 'tom' }
const obj2 = { age: 34 }
const obj3 = Object.assign(obj, obj1, obj2)
console.log(obj3)
{name: 'tom', age: 34}
age: 34
name: "tom"
手寫深拷貝
function deepClone (obj) {
let newObj
if (obj && typeof(obj) !== 'object') {
newObj = obj
} else if (obj && typeof(obj) === 'object') {
newObj = Array.isArray(obj) ? []: {}
for(let key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof(obj[key]) === 'object') {
newObj[key] = deepClone(obj[key])
} else {
newObj[key] = obj[key]
}
}
}
}
return newObj
}
let test = {
x : 1,
y : 2,
z : {
a : 4,
b : 5
}
}
const result = deepClone(test)
test.x = 5
console.log(test,result)
{x: 5, y: 2, z: {…}} {x: 1, y: 2, z: {…}}