Visitar URL original
learned and finished day14 · soyaine/JavaScript30@44504d7 · GitHub
Skip to content

Commit 44504d7

Browse files
committed
learned and finished day14
1 parent 10e8ea6 commit 44504d7

1 file changed

Lines changed: 60 additions & 2 deletions

File tree

‎14 - JavaScript References VS Copying/index-START.html‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,28 @@
88

99
<script>
1010
// 从 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);
1122

1223
// 首先我们有一个数组
1324
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
1425

1526
// 现在我们想要复制它
27+
const team = players;
28+
console.log(players, team);
1629

1730
// 也许你觉得可以直接这样修改复制后的数组:
31+
team[2] = 'Lex';
32+
console.log(players, team);
1833

1934
// 但我们修改这个数组的时候会发生什么呢?
2035

@@ -25,27 +40,70 @@
2540
// 为什么?因为 team 只是这个数组的引用,并不是它的复制。team 和 players 指向的是同一个数组。
2641

2742
// 所以如何解决这个问题?下面来进行真正的复制吧。
43+
const team2 = players.slice();
2844

2945
// one day
3046

3147
// 或者创建一个新数组,然后用 concat 方法来获取它
48+
const team3 = [].concat(players);
3249

3350
// 再或者用 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);
3458

3559
// 现在再修改 team5,原数组不会变了
3660

3761
// 对 Object 类型的数据来说也是一样的,我们用一个 person 例子来说明
3862

39-
// 现在又一个 Object 对象
63+
// 现在有一个 Object 对象
64+
const person = {
65+
name: 'Alex',
66+
age: '80'
67+
};
4068

4169
// 然后以为这样可以复制它:
4270

4371
// 到底要怎样才能真正得到它的复制版呢?
72+
const person2 = Object.assign({},person,{age:18, number:10});
73+
console.log(person,person2);
4474

4575
// 我们满怀期望的希望扩展语法对它也会生效
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);
4692

4793
// 需要注意的是:这里的例子里面,我们用的数组和对象都只是一层嵌套,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);
49107
</script>
50108

51109
</body>

0 commit comments

Comments
 (0)