前端ES6对象运算符扩展(深拷贝与合并对象)

传统使用 let student2 = student1,是浅拷贝(引用),改变了student2的属性,也会改变student1的属性

如果想要对象不相互关联,需要使用深拷贝,语法是: let student2 = (...student1)

实例演示:

			 let student1 = {name: "李华", age: 18};
            {
                //传统引用,两个学生对象输出的name都为小明
                let student2 = student1;
                student2.name = "小明";
                console.log("student1=>", student1);
                console.log("student2=>", student2);//
            }
            let student ={name: "李华", age: 18};
            {
                // 拷贝对象(深拷贝),只有第二个学生对象输出的是小明
                let student2 = {...student};
                student2.name = "小明";
                console.log("student1=>", student);
                console.log("student2=>", student2);
            }
            {
                // 合并对象[深拷贝],两个对象合并也是深拷贝,不会影响原来对象
                let stu = {name: "小红", age: 18};
                let car = {brand: "奔驰", price: 800000};
                let stu_car = {...stu, ...car}
                stu_car.brand = "比亚迪";
                console.log("stu=>", stu);
                console.log("stu_car=>", stu_car);
            }

你可能感兴趣的:(前端技术,es6,前端,ecmascript)