|
8 | 8 |
|
9 | 9 | <script>
|
10 | 10 | // start with strings, numbers and booleans
|
| 11 | + let age = 100; |
11 | 12 |
|
12 | 13 | // Let's say we have an array
|
13 | 14 | const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
|
14 | 15 |
|
15 | 16 | // and we want to make a copy of it.
|
| 17 | + const team = players; |
| 18 | + console.log(players, team); |
16 | 19 |
|
17 | 20 | // You might think we can just do something like this:
|
| 21 | + team[3] = 'Lux'; //updating an array will always reference back |
18 | 22 |
|
19 | 23 | // however what happens when we update that array?
|
20 | 24 |
|
|
25 | 29 | // Why? It's because that is an array reference, not an array copy. They both point to the same array!
|
26 | 30 |
|
27 | 31 | // So, how do we fix this? We take a copy instead!
|
| 32 | + const team2 = players.slice(); //makes a copy(entire array) |
28 | 33 |
|
29 | 34 | // one day
|
30 | 35 |
|
| 36 | + |
31 | 37 | // or create a new array and concat the old one in
|
| 38 | + const team3 = [].concat(players); |
32 | 39 |
|
33 | 40 | // or use the new ES6 Spread
|
| 41 | + const team4 = [...players]; |
| 42 | + team4[3] = 'wacko'; |
| 43 | + console.log(team4); |
34 | 44 |
|
35 | 45 | // now when we update it, the original one isn't changed
|
| 46 | + const team5 = Array.from(players); |
36 | 47 |
|
37 | 48 | // The same thing goes for objects, let's say we have a person object
|
38 | 49 |
|
39 | 50 | // with Objects
|
| 51 | + const dog = { |
| 52 | + name: 'Porter', |
| 53 | + age: 5 |
| 54 | + }; |
40 | 55 |
|
41 | 56 | // and think we make a copy:
|
| 57 | + const captain = dog; |
| 58 | + captain.age = 99; |
42 | 59 |
|
43 | 60 | // how do we take a copy instead?
|
| 61 | + const cap2 = Object.assign({}, dog, { age: 100}); |
| 62 | + console.log(cap2); |
44 | 63 |
|
45 | 64 | // We will hopefully soon see the object ...spread
|
46 | 65 |
|
47 | 66 | // 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.
|
| 67 | + const porter = { |
| 68 | + name: 'Porter', |
| 69 | + social: { |
| 70 | + twitter: '@porter', |
| 71 | + facebook: 'porter.dog' |
| 72 | + } |
| 73 | + }; |
| 74 | + console.clear(); |
| 75 | + console.log(porter); |
| 76 | + |
| 77 | + const special = Object.assign({}, porter); |
| 78 | + console.log(special,'super'); |
| 79 | + |
| 80 | + //to make a deep copy |
| 81 | + |
| 82 | + const dev = Object.assign({}, porter); |
| 83 | + const dev2 = JSON.parse(JSON.stringify(porter)); |
| 84 | + |
| 85 | + console.log(dev,dev2); |
48 | 86 |
|
49 | 87 | </script>
|
50 | 88 |
|
|
0 commit comments