-
Notifications
You must be signed in to change notification settings - Fork 41.8k
Expand file tree
/
Copy pathindex-START.html
More file actions
104 lines (74 loc) · 2.35 KB
/
index-START.html
File metadata and controls
104 lines (74 loc) · 2.35 KB
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
98
99
100
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Reference VS Copy</title>
<link rel="icon" href="https://fav.farm/🔥" />
</head>
<body>
<script>
// start with strings, numbers and booleans
let age = 100;
let age2=age;
console.log(age,age2);
age =200;
console.log(age,age2);
// Let's say we have an array
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
// and we want to make a copy of it.
const team =players;
console.log(team);
const team2 = players.slice();
const team3 = [].concat(players);
const team4 = [...players];
const team5 = Array.from(players);
team2[3]='gem';
team3[2]='hox';
team4[3]='ha ha ha';
// You might think we can just do something like this:
// team[3]='lus';
// console.log(players);
// however what happens when we update that array?
// 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!
// one way
// or create a new array and concat the old one in
// or use the new ES6 Spread
// now when we update it, the original one isn't changed
// The same thing goes for objects, let's say we have a person object
// with Objects
const person = {
name: 'Wes Bos',
age: 80
};
// const captain = person;
// captain.age = 99;
const cap2 = Object.assign({},person);
cap2.age =99;
cap2.number = 23;
cap2['phone'] = 0173473648;
Object.assign(cap2,{id:1});
const cap3 = {...person};
cap3.number = 3792;
const hlw = {
name:'dip',
age:100,
social:{
twitter:'@hello',
facebook:'hello world'
}
}
const hlw2 = Object.assign({},hlw);
hlw2.id = 123;
const hlw3 = JSON.parse(JSON.stringify(hlw));
hlw3.social.insta = 'helloagain';
const hlw4 = JSON.stringify(hlw); //not a object anymore.its a string
// and think we make a copy:
// how do we take a copy instead?
// We will hopefully soon see the object ...spread
// 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.
</script>
</body>
</html>