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
// You might think we can just do something like this:
33
+
// team[3] = 'Lux';
16
34
17
-
// You might think we can just do something like this:
35
+
// however what happens when we update that array?
18
36
19
-
// however what happens when we update that array?
37
+
// now here is the problem!
20
38
21
-
// now here is the problem!
39
+
// oh no - we have edited the original array too!
22
40
23
-
// oh no - we have edited the original array too!
41
+
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
24
42
25
-
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
43
+
// So, how do we fix this? We take a copy instead!
44
+
constteam2=players.slice();
26
45
27
-
// So, how do we fix this? We take a copy instead!
46
+
// one way
28
47
29
-
// one way
48
+
// or create a new array and concat the old one in
49
+
constteam3=[].concat(players);
30
50
31
-
// or create a new array and concat the old one in
51
+
// or use the new ES6 Spread
52
+
constteam4=[...players];
53
+
team4[3]='heeee hawww';
54
+
console.log(team4);
32
55
33
-
// or use the new ES6 Spread
56
+
constteam5=Array.from(players);
34
57
35
-
// now when we update it, the original one isn't changed
58
+
// now when we update it, the original one isn't changed
36
59
37
-
// The same thing goes for objects, let's say we have a person object
60
+
// The same thing goes for objects, let's say we have a person object
38
61
39
-
// with Objects
40
-
constperson={
41
-
name: 'Wes Bos',
42
-
age: 80
43
-
};
62
+
// with Objects
63
+
constperson={
64
+
name: 'Wes Bos',
65
+
age: 80
66
+
};
44
67
45
-
// and think we make a copy:
68
+
// and think we make a copy:
69
+
// const captain = person;
70
+
// captain.number = 99;
46
71
47
-
// how do we take a copy instead?
72
+
// how do we take a copy instead?
73
+
constcap2=Object.assign({},person,{
74
+
number: 99,
75
+
age: 12
76
+
});
77
+
console.log(cap2);
48
78
49
-
// We will hopefully soon see the object ...spread
79
+
// We will hopefully soon see the object ...spread
80
+
// const cap3 = {...person};
50
81
51
-
// 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.
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