-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-START.html
97 lines (73 loc) · 2.42 KB
/
index-START.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Reference VS Copy</title>
</head>
<body>
<script>
// start with strings, numbers and booleans
// COPY
let age = 100;
let age2 = age;
console.log(age, age2);
age = 200;
console.log(age, age2);
// Let's say we have an array
// REFERENCE
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
// and we want to make a copy of it.
const team = players;
console.log(players, team);
// You might think we can just do something like this:
// team[3] = 'lux';
// console.log(players, team);
// however what happens when we update that array?
// changes on both players and team
// now here is the problem!
// oh no - we have edited the original array too!
// Why? It's because that is an array reference, not an array copy. They both point to the same array!
// So, how do we fix this? We take a copy instead!
const team2 = players.slice();
// one way
// or create a new array and concat the old one in
const team3 = [].concat(players);
// or use the new ES6 Spread
const team4 = [...players];
// now when we update it, the original one isn't changed
team4[3] = "yay";
console.log(team4, players);
const team5 = Array.from(players);
// The same thing goes for objects, let's say we have a person object
// with Objects
const person = {
name: 'Wes Bos',
age: 80
};
// and think we make a copy:
const captain = person;
// captain.number = 99;
// console.log(person);
// how do we take a copy instead?
const captain2 = Object.assign({}, person, {number : 99, age : 12});
console.log(captain2);
// We will hopefully soon see the object ...spread
// const cap3 = {...person}; not available yet
// 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.
const wes = {
name: 'Wes',
age: 100,
social: {
twitter: '@wesbos',
facebook: 'wesbos.developer'
}
}
console.log(wes);
const dev = Object.assign({}, wes);
console.log(dev);
// dev.social.twitter = "lol" >>> will change wes object too
// convert to string then object will give full deep clone, but slow?
const dev2 = JSON.parse(JSON.stringify(wes));
</script>
</body>
</html>