-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
82 lines (61 loc) · 2.38 KB
/
index.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fundamentals Reference vs Copy</title>
</head>
<body>
<center>
<h1> Js Fundamentals : Reference vs Copy</h1>
</center>
<script>
// start with strings, numbers and booleans
// Let's say we have an array
const players = ['Mario', 'Luigi', 'Deadpool', 'Poopman'];
// and we want to make a copy of it.
// You might think we can just do something like this:
// however what happens when we update that array?
// 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!
// one way
const players2 = players.slice();
// or create a new array and concat the old one in
const player3 = [].concat(players);
// or use the new ES6 Spread
const player4 = [...players];
// now when we update it, the original one isn't changed
const players5 = Array.from(players);
// The same thing goes for objects, let's say we have a person object
players4[3] = "lol";
console.log("copy", players4, "original :", players);
// with Objects
const person = {
name: 'Mario Bros',
age: 40
};
// and think we make a copy:
// how do we take a copy instead?
const shallowCopy = Object.assign({}, person, { number: 11, age: 23 })
console.log("original :", person, " updated :", shallowCopy);
// We will hopefully soon see the object ...spread
const copyOfObject = { ...person }
// 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 nestedObject = {
name: 'yuan',
age: 10,
social: {
twitter: '@yuan',
facebook: 'yuan.player'
}
};
console.clear();
console.log(nestedObject);
// cheap trick
const dev = Object.assign({}, nestedObject);
const dev2 = JSON.parse(JSON.stringify(nestedObject));
console.table(dev2);
</script>
</body>
</html>