|
8 | 8 |
|
9 | 9 | <script>
|
10 | 10 | // start with strings, numbers and booleans
|
| 11 | + // let age = 100; |
| 12 | + // let age2 = age; |
| 13 | + // console.log(age, age2); |
| 14 | + // age = 200; |
| 15 | + // console.log(age, age2); |
| 16 | + |
| 17 | + // let name = 'Wes'; |
| 18 | + // let name2 = name; |
| 19 | + // console.log(name, name2); |
| 20 | + // name = 'wesley'; |
| 21 | + // console.log(name, name2); |
11 | 22 |
|
12 | 23 | // Let's say we have an array
|
13 | 24 | const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
|
14 | 25 |
|
15 | 26 | // and we want to make a copy of it.
|
| 27 | + const team = players; |
16 | 28 |
|
| 29 | + console.log(players, team); |
17 | 30 | // You might think we can just do something like this:
|
| 31 | + // team[3] = 'Lux'; |
18 | 32 |
|
19 | 33 | // however what happens when we update that array?
|
20 | 34 |
|
|
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(); |
28 | 43 |
|
29 | 44 | // one way
|
30 | 45 |
|
31 | 46 | // or create a new array and concat the old one in
|
| 47 | + const team3 = [].concat(players); |
32 | 48 |
|
33 | 49 | // or use the new ES6 Spread
|
| 50 | + const team4 = [...players]; |
| 51 | + team4[3] = 'heeee hawww'; |
| 52 | + console.log(team4); |
| 53 | + |
| 54 | + const team5 = Array.from(players); |
34 | 55 |
|
35 | 56 | // now when we update it, the original one isn't changed
|
36 | 57 |
|
|
43 | 64 | };
|
44 | 65 |
|
45 | 66 | // and think we make a copy:
|
| 67 | + // const captain = person; |
| 68 | + // captain.number = 99; |
46 | 69 |
|
47 | 70 | // how do we take a copy instead?
|
| 71 | + const cap2 = Object.assign({}, person, { number: 99, age: 12 }); |
| 72 | + console.log(cap2); |
48 | 73 |
|
49 | 74 | // We will hopefully soon see the object ...spread
|
| 75 | + // const cap3 = {...person}; |
50 | 76 |
|
51 | 77 | // 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.
|
52 | 78 |
|
| 79 | + const wes = { |
| 80 | + name: 'Wes', |
| 81 | + age: 100, |
| 82 | + social: { |
| 83 | + twitter: '@wesbos', |
| 84 | + facebook: 'wesbos.developer' |
| 85 | + } |
| 86 | + }; |
| 87 | + |
| 88 | + console.clear(); |
| 89 | + console.log(wes); |
| 90 | + |
| 91 | + const dev = Object.assign({}, wes); |
| 92 | + |
| 93 | + const dev2 = JSON.parse(JSON.stringify(wes)); |
| 94 | + |
| 95 | + |
53 | 96 | </script>
|
54 | 97 |
|
55 | 98 | </body>
|
|
0 commit comments