|
8 | 8 |
|
9 | 9 | <script> |
10 | 10 | // 从 String、Number、Boolean 类型的值开始: |
| 11 | + let age = 100; |
| 12 | + let age2 = age; |
| 13 | + console.log(age, age2); |
| 14 | + age2 = 200; |
| 15 | + console.log(age, age2); |
| 16 | + |
| 17 | + let name = 'ruby'; |
| 18 | + let name2 = name; |
| 19 | + console.log(name, name2); |
| 20 | + name = 'tom'; |
| 21 | + console.log(name, name2); |
11 | 22 |
|
12 | 23 | // 首先我们有一个数组 |
13 | 24 | const players = ['Wes', 'Sarah', 'Ryan', 'Poppy']; |
14 | 25 |
|
15 | 26 | // 现在我们想要复制它 |
| 27 | + const team = players; |
| 28 | + console.log(players, team); |
16 | 29 |
|
17 | 30 | // 也许你觉得可以直接这样修改复制后的数组: |
| 31 | + team[2] = 'Lex'; |
| 32 | + console.log(players, team); |
18 | 33 |
|
19 | 34 | // 但我们修改这个数组的时候会发生什么呢? |
20 | 35 |
|
|
25 | 40 | // 为什么?因为 team 只是这个数组的引用,并不是它的复制。team 和 players 指向的是同一个数组。 |
26 | 41 |
|
27 | 42 | // 所以如何解决这个问题?下面来进行真正的复制吧。 |
| 43 | + const team2 = players.slice(); |
28 | 44 |
|
29 | 45 | // one day |
30 | 46 |
|
31 | 47 | // 或者创建一个新数组,然后用 concat 方法来获取它 |
| 48 | + const team3 = [].concat(players); |
32 | 49 |
|
33 | 50 | // 再或者用 ES6 里面的扩展语法 |
| 51 | + const team4 = [...players]; |
| 52 | + const team5 = Array.from(players); |
| 53 | + team2[2]='hello'; |
| 54 | + team3[3]='hello'; |
| 55 | + team4[4]='hello'; |
| 56 | + team5[4]='hello'; |
| 57 | + console.log(team2, team3, team4, team5); |
34 | 58 |
|
35 | 59 | // 现在再修改 team5,原数组不会变了 |
36 | 60 |
|
37 | 61 | // 对 Object 类型的数据来说也是一样的,我们用一个 person 例子来说明 |
38 | 62 |
|
39 | | - // 现在又一个 Object 对象 |
| 63 | + // 现在有一个 Object 对象 |
| 64 | + const person = { |
| 65 | + name: 'Alex', |
| 66 | + age: '80' |
| 67 | + }; |
40 | 68 |
|
41 | 69 | // 然后以为这样可以复制它: |
42 | 70 |
|
43 | 71 | // 到底要怎样才能真正得到它的复制版呢? |
| 72 | + const person2 = Object.assign({},person,{age:18, number:10}); |
| 73 | + console.log(person,person2); |
44 | 74 |
|
45 | 75 | // 我们满怀期望的希望扩展语法对它也会生效 |
| 76 | + const person3 = {...person}; |
| 77 | + person3['phone'] = '159x'; |
| 78 | + console.log(person, person3); |
| 79 | + |
| 80 | + const cop = { |
| 81 | + name: 'A', |
| 82 | + time:{ |
| 83 | + workday: '9-11', |
| 84 | + weekend: '10-12' |
| 85 | + } |
| 86 | + }; |
| 87 | + const cop2 = {...cop}; |
| 88 | + console.log(cop,cop2); |
| 89 | + cop2['time']['workday']='8-10'; |
| 90 | + cop2['name'] = 'B'; //只有第一层有效 |
| 91 | + console.log(cop, cop2); |
46 | 92 |
|
47 | 93 | // 需要注意的是:这里的例子里面,我们用的数组和对象都只是一层嵌套,Lodash 有一个深度复制的方法,但你使用之前需要多考虑一下。 |
48 | | - |
| 94 | + const alex = { |
| 95 | + name: 'Alex', |
| 96 | + age: 20, |
| 97 | + social: { |
| 98 | + twitter: '@alex', |
| 99 | + facebook: 'alex.fb' |
| 100 | + } |
| 101 | + }; |
| 102 | + const alex2 = Object.assign({},alex); |
| 103 | + const alex3 = JSON.parse(JSON.stringify(alex)); |
| 104 | + alex2['social']['twitter'] = '@new'; |
| 105 | + alex3['social']['facebook'] = 'new.fb'; |
| 106 | + console.log(alex,alex2,alex3); |
49 | 107 | </script> |
50 | 108 |
|
51 | 109 | </body> |
|
0 commit comments