首先
let arr1 = [1, 2, 3];
let arr2 = arr1;
肯定是不行的
记录一下几种简单的方法.
let arr2 = [...arr1];
let arr2 = arr1.concat();
let arr2 = arr1.slice();
顺便写一下自己写的对象深拷贝的方法,
const test = {
info: {
name: 'kobe',
nums: [1,2,3]
}
}
test.loop = test;
function isObj(obj) {
return typeof obj === 'object' && obj !== null;
}
// weakSet防止循环引用
function deepClone(source, set = new WeakSet) {
console.log(source);
if(set.has(source)) {
return source;
}
const obj = Array.isArray(source) ? [] : {};
set.add(source);
for(let key in source) {
obj[key] = isObj(source[key]) ? deepClone(source[key], set) : source[key];
}
return obj;
}
let new_test = deepClone(test);
test.info.nums.push(4);
console.log(new_test);
// JSON方式能实现简单的深拷贝,但是无法解决循环引用。
// 在JSON.stringify的时候很多规则会使最后JSON.parse出来的对象不太一样。
// 例如会忽略undefined,总的说转成JSON字符串的时候,要让大多数语言理解,就不能存在undefined, NaN这种
const person1 = {
name: 'hello',
gender: 'male'
}
const person2 = null;
const json_obj = {
info: {
name: 'kobe',
nums: [1,2,3]
},
persons: [person1, person2]
}
let obj = JSON.parse(JSON.stringify(json_obj));
console.log(obj);