ECMAScript中的浅拷贝和深拷贝

在这里插入图片描述

一.什么是浅拷贝,什么是深拷贝

浅拷贝:浅拷贝是将原始对象中的数据型字段拷贝到新对象中去,将引用型字段的“引用”复制到新对象中去,不把“引用的对象”复制进去,所以原始对象和新对象引用同一对象,新对象中的引用型字段发生变化会导致原始对象中的对应字段也发生变化。

深拷贝:深拷贝:深拷贝是在引用方面不同,深拷贝就是创建一个新的和原始字段的内容相同的字段,是两个一样大的数据段,所以两者的引用是不同的,之后的新对象中的引用型字段发生改变,不会引起原始对象中的字段发生改变。

二.实现浅拷贝的几种方法

1.直接赋值给1个变量

let str = "abcd";
let str1 = str;
str1 = 'test';
console.log(str);//abcd
console.log(str1);//test

2.使用ES6中 Obj.assign()方法

let obj1 = {
  username: 'loki',
};
let obj2 = Object.assign(obj1);
obj2.username = 'Jack';
console.log(obj1.username);//Jack

3.使用ES6中的Array.prototype.concat()方法

let arr1 = [1, 3, 4, 5, { username: "optimus prime" }];
let arr2 = arr1.concat();
arr2[4].username = 'Megatron';
console.log(arr1[4].username);//Megatron

4.使用ES6中三点运算符 ‘…’实现浅拷贝 案例如下

let arr1 = [1, 5, 6, 7, 8];
let arr3 = [{ username: "Megatron" }, 10, 11, 12];
let arr4 = [...arr1, ...arr3];
arr4[5].username = "Loki";
console.log(arr3);//Loki

5.使用Array.prototype.slice()
let arr5 = [1, 2, 3, 4, 5, 6,{username : "Loki"}];
let arr6 = arr5.slice();

三、实现深拷贝的几种方法

1.使用JSON实现深拷贝

let arr2 = ['third', 20, 10, 'Loki'];

let arr3 = JSON.parse(JSON.stringify(arr2));
arr3[2] = 100;
console.log(arr2)//10 

2.使用JSON实现深拷贝遇到的问题

在使用被拷贝的数据不能有function 如果有的话 会转换成null如下所示
let arr5 = ["first", 'second', { username: "Loki" }, function fun() { }, 10];
let arr6 = JSON.parse(JSON.stringify(arr5));
console.log(arr6[3]);//null  

3.通过递归实现深拷贝

    function checkType(target) {
    //通过这个函数拿到数据类型
     	return Object.prototype.toString.call(target).slice(8, -1);
    }
    function clone(target) {
        let result, targetType = checkType(target);
        if (targetType === "Object") {
            result = {};
        } else if (targetType === "Array") {
            result = [];
        } else {
            return target
        }
        for (let i in target) {
            let value = target[i];
            if (checkType(value) === "Object" || checkType(value) === "Array") {
                clone(value);
            } else {
                result[i] = value;
            }
        }
        return result;
    };
   let arr6 = ['string', 123, true, undefined, null, function fun() {}, {username: 'Loki'}];
   let arr7 = clone(arr6);
   console.log(arr7);//'string', 123, true, undefined, null, function fun() {}, {username: 'Loki'}

猜你喜欢

转载自blog.csdn.net/handsomezhanghui/article/details/104214289
今日推荐