JS基础——深拷贝与浅拷贝

浅拷贝

对象的浅拷贝

  • Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象,它将返回目标对象。
var target = { name:"rlxu",borth: {year: "1991"}};
var obj = Object.assign(target);
obj.name = "xuriliang";
console.log(target.name);
obj.borth.year = "1990"; //无法深拷贝
console.log(target.borth.year);
  • ... 扩展运算符。
var target = { name:"rlxu",borth: {year: "1991"}};
var obj = {...target};
obj.name = "xuriliang";
console.log(target.name);
obj.borth.year = "1990"; //无法深拷贝
console.log(target.borth.year);
  • Object.defineProperties
const source = {name: "rlxu",borth: {year: "1991"}}
const obj = {}
Object.defineProperties(obj,Object.getOwnPropertyDescriptors(source))

数组的浅拷贝

  • concact方法不会改变现有的数组,而仅仅会返回被连接数组的一个副本。可以通过[].contact()来实现数组的浅拷贝。
var arr = [1,2,3,4];
var copyArr = [].concat(arr);
copyArr[0] = "5"
console.log(arr[0])
  • slice方法可从已有的数组中返回选定的元素,该方法并不会修改数组,而是返回一个子数组。
var arr = [1,2,3,4];
var copyArr = arr.slice(0);
copyArr[0] = "5"
console.log(arr[0])
  • Object.defineProperties
var arr = [1,{name: "rlxu"}]
var cloneArr = [];
Object.defineProperties(cloneArr,Object.getOwnPropertyDescriptors(arr))

深拷贝

  • JSON.stringify,通过使用JSON.parse(JSON.stringify(data))可以进行深入拷贝。
var target = {name:"rlxu",borth: { year: "1991"} };
var obj = JSON.parse(JSON.stringify(target));
obj.name = "xuriliang";
console.log(target.name);
obj.borth.year = "1990";
console.log(target.borth.year)
  • for循环递归
function deepClone(obj) {
    var target = {};
    for(var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            if (typeof obj[key] === 'object') {
                target[key] = deepClone(obj[key]); 
            } else {
                target[key] = obj[key];
            }
        }
    }
    return target;
}
var target = { name:"rlxu",borth: {year: "1991"}};
var obj = deepClone(target);
obj.borth.year = "1990";
console.log(target.borth.year)

你可能感兴趣的:(javascript,深拷贝)