You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 14 - JavaScript References VS Copying/index-Harry.html
+30-1
Original file line number
Diff line number
Diff line change
@@ -29,10 +29,19 @@
29
29
// So, how do we fix this? We take a copy instead!
30
30
31
31
// one way
32
+
// 完整複製一個不是 reference 的陣列: 方法1:
33
+
constteam2=players.slice();
32
34
33
35
// or create a new array and concat the old one in
36
+
// 方法2:
37
+
constteam3=[].concat(players);
34
38
35
39
// or use the new ES6 Spread
40
+
// 方法3:
41
+
constteam4=[...players];
42
+
43
+
// 方法4:
44
+
constteam5=Array.from(players);
36
45
37
46
// now when we update it, the original one isn't changed
38
47
@@ -45,14 +54,34 @@
45
54
};
46
55
47
56
// and think we make a copy:
57
+
// 方法1:
58
+
constperson2=Object.assign({},person,{
59
+
height: 172
60
+
});
61
+
62
+
// 方法2:
63
+
constcap3={
64
+
...person
65
+
};
48
66
49
67
// how do we take a copy instead?
68
+
constwes={
69
+
name: 'Wes',
70
+
age: 100,
71
+
social: {
72
+
twitter: '@wesbos',
73
+
facebook: 'wesbos.developer'
74
+
}
75
+
};
50
76
51
77
// We will hopefully soon see the object ...spread
78
+
constdev=Object.assign({},wes);
79
+
80
+
constdev2=JSON.parse(JSON.stringify(wes));
52
81
53
82
// Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.
0 commit comments