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