1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| /**
* 为方便讲解和学习,引入 lodash 的深拷贝和浅拷贝函数
* 以下代码可在浏览器控制台运行
*/
const importJS = document.createElement('script');
importJS.setAttribute("src", 'https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js');
document.getElementsByTagName("head")[0].appendChild(importJS);
// 等待 lodash 加载。要在浏览器使用,有什么好的办法吗?
setTimeout(() => {
if (typeof _ === 'function') {
// 现在有个数组 list,它里面有“a、b、c”,3 个变量,如下:
const a = {
name: 'a',
value: 'a'
};
const b = 'str';
let c = 256;
const list = [a, b, c];
const listCopy = list; // 引用赋值
const listDeep = _.cloneDeep(list); // 深拷贝
const listClone = _.clone(list); // 浅拷贝
list.push('d'); // list、 listCopy(赋值) 受影响
a.name = 'new a'; // list、listClone(浅) 和 listCopy(赋值) 受影响
listClone.push('e'); // listClone(浅)受影响
c = 480; // 都不受影响
listDeep.push('f'); // listDeep(深)受影响
list[0].value = 'new a'; // list、listClone(浅) 和 listCopy(赋值) 受影响
list[1] = 'new str'; // list、listCopy(赋值) 受影响
console.log('list', list); // [{name: "new a", value: "new a"}, "new str", 256, "d"]
console.log('listCopy', listCopy); // [{name: "new a", value: "new a"}, "new str", 256, "d"]
console.log('listDeep', listDeep); // [{name: "a", value: "a"}, "str", 256, "f"]
console.log('listClone', listClone); // [{name: "new a", value: "new a"}, "str", 256, "e"]
}
}, 1000);
|