浅拷贝的实现方式
Posted coderkey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浅拷贝的实现方式相关的知识,希望对你有一定的参考价值。
一,Object.assign() 方法
const oldObj =
name: "coderkey",
age: 18,
hobbies: ["eat", "sleep", "game"],
;
//将拷贝对象与空对象合并
const newObj = Object.assign(,oldObj)
console.log(newObj);
oldObj.name = 'pink'
console.log(oldObj.hobbies === newObj.hobbies);
oldObj.hobbies[0] = "play";
console.log(oldObj,newObj);
二,ES6展开运算符…
const oldObj =
name: "coderkey",
age: 18,
hobbies: ["eat", "sleep", "game"],
;
const newObj= ...oldObj ;
console.log(newObj);
oldObj.name = 'pink'
console.log(oldObj.hobbies === newObj.hobbies);
oldObj.hobbies[0] = "play";
console.log(oldObj,newObj);
三,数组合并方法 concat()
const oldArr = [ 1,2,3,name:'coderkey',age:18]
const newArr = oldArr.concat()
oldArr[0] = 0
oldArr[3].name = 'pink'
newArr[3].age = 25
console.log(oldArr[3] === newArr[3]);
console.log(oldArr,newArr);
四,数组剪裁方法 slice()
const oldArr = [ 1,2,3,name:'coderkey',age:18]
const newArr = oldArr.slice()
oldArr[0] = 0
oldArr[3].name = 'pink'
newArr[3].age = 25
console.log(oldArr[3] === newArr[3]);
console.log(oldArr,newArr);
五,注意:
浅拷贝拷贝的是引用,它们共享同一块内存,当引用的值改变时,另外一个也会跟着改变;
以上是关于浅拷贝的实现方式的主要内容,如果未能解决你的问题,请参考以下文章