<script src="./lodash.min.js"></script>
<script>
// 深拷贝
const obj = {
name: 'hello',
age: 14,
hi: undefined,
eat: () => { },
arr: [1, 2, 3, 4],
min: {
son: 'vite'
}
}
// 1、序列化 反序列化 JSON.parse(JSON.stringify())
// 缺点:属性值是undefined和function的属性会删除
const newObj1 = JSON.parse(JSON.stringify(obj));
newObj1.min.son = "pinia";
// hi属性和eat属性被删掉了
console.log(newObj1); // { "name": "hello", "age": 14, "arr": [1,2,3,4], "min": { "son": "pinia" } }
// 2、lodash的 _.cloneDeep()
// 不会删除属性
// 缺点:需要引入第三方库
const newObj2 = _.cloneDeep(obj);
newObj2.min.son = "ts";
console.log(newObj2);
// 3、全局的structuredClone()
// 缺点:对象的属性值时方法时会报错
// const newObj3 = structuredClone(obj);
// newObj3.min.son = "js";
// console.log(newObj3); // Uncaught DOMException: Failed to execute 'structuredClone' on 'Window': () => { } could not be cloned.
console.log(obj);
// 4、自己手写递归函数实现深拷贝
const obj1 = {
name: 'hello',
test: {
age: 12
}
}
const arr = [1, 2, 3, { name: 'vite' }];
function cloneDeep(oldObj) {
const newObj = Array.isArray(oldObj) ? [] : {};
for (let i in oldObj) {
if (typeof oldObj[i] === 'object') {
newObj[i] = cloneDeep(oldObj[i]);
} else {
newObj[i] = oldObj[i];
}
}
return newObj;
}
const result1 = cloneDeep(obj1);
result1.test.age = 15;
console.log(result1);
console.log(obj1);
const result2 = cloneDeep(arr);
result2[3].name = "ts";
console.log(result2);
console.log(obj);
</script>
21、js - 面试 - 深拷贝
猜你喜欢
转载自blog.csdn.net/EchoLiner/article/details/131067872
今日推荐
周排行