深拷贝
function deepClone(obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
if (obj instanceof Date) {
return new Date(obj);
}
if (obj instanceof Array) {
const cloneArray = [];
for (let i = 0; i < obj.length; i++) {
cloneArray[i] = deepClone(obj[i]);
}
return cloneArray;
}
if (obj instanceof Object) {
const cloneObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key]);
}
}
return cloneObj;
}
}
在实际开发中通常不会这么使用深拷贝,ES6 中的 JSON.parse(JSON.stringify(obj))也可以用于深拷贝,但有一定的限制比如不能用于复制函数和循环引用
function deepClone2(obj) {
const cloneObj = JSON.parse(JSON.stringify(obj));
return cloneObj;
}
验证
const originalObject = {
name: "John",
age: 30,
address: {
city: "New York",
country: "USA",
},
hobbies: ["reading", "traveling"],
};
const copiedObject = deepClone(originalObject);
console.log(copiedObject);
浅拷贝
function shallowClone(obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
if (obj instanceof Array) {
const cloneArray = [];
for (let i = 0; i < obj.length; i++) {
cloneArray[i] = obj[i];
}
return cloneArray;
}
if (obj instanceof Object) {
const cloneObject = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObject[key] = obj[key];
}
}
return cloneObject;
}
}
浅拷贝与深拷贝的区别在于,深拷贝是层级式的将原数据完全拷贝成为一份新的数据,浅拷贝仅仅是对数据的第一层进行拷贝。当改变拷贝数据的深层数据时,浅拷贝会影响原数据而深拷贝不会影响原数据。
验证
const originalObject = {
name: "John",
age: 30,
hobbies: ["reading", "traveling"],
};
const copiedObject = shallowClone(originalObject);
console.log(copiedObject);
copiedObject.name = "Alice";
copiedObject.hobbies.push("swimming");
console.log(originalObject);