深拷贝、浅拷贝
浅拷贝:将值的引用指向新的变量,当新的变量的值有改动,那么被拷贝的变量的值也会跟着 变动
深拷贝:申请一个新的内存空间,将被拷贝的值复制到新的内存中。拷贝变量的值改变,被拷贝的变量的值 不会改变
实现深度拷贝
1、JSON.stringify()
function deepClone(obj) { let temp = JSON.stringify(obj); let result = JSON.parse(temp); return result; }
2、for...in 遍历和复制
function deepClone(obj) { let result = typeof obj.splice === "function" ? [] : {}; if( obj && typeof obj === 'object' ) { for( let key in obj) { if (obj[key] && typeof obj[key] === 'object') { result[key] = deepClone(obj[key]); } else { result[key] = obj[key]; } } return result; } return obj; }
3、Array.prototype.forEach
function deepClone(obj) { let copy = Object.create(Object.getPrototypeOf(obj)); let propNames = Object.getOwnPropertyNames(obj); propNames.forEach(function (items) { let item = Object.getOwnPropertyDescriptor(obj, items); Object.defineProperty(copy, items, item); }); return copy; }
实现浅拷贝
Object.assign()
如果对象或者数组只有一级属性,没有二级属性,那么assign()方法是深拷贝。像下面的第一个例子
如果有二级属性,那么二级以后的属性就是浅拷贝。下面的第二个例子
let a = ["ASD", "666", "ECC", "BCC"]; let b = []; Object.assign(b, a); b[0] = "QQQ"; console.log(`Value of a: ${a}, Value of b: ${b}`); // Value of a: ["ASD", "666", "ECC", "BCC"], Value of b: ["QQQ", "666", "ECC", "BCC"] let a = a = ["ASD", "666", "ECC", "BCC", {"name": 1, "age": 2}] let b = []; Object.assign(b, a); b[4].name = "QQQ"; console.log(`Value of a: ${a}, Value of b: ${b}`); // Value of a: ["ASD", "666", "ECC", "BCC", {"name": "QQQ", "age": 2}], Value of b: ["ASD", "666", "ECC", "BCC", {"name": "QQQ", "age": 2}]