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