|
12 | 12 |
|
13 | 13 | // Cloning Arrays
|
14 | 14 | // 1st way : Spread Operator
|
15 | | -const numbers = [1, 2, 3, 4]; |
16 | | -const copiedNumbers = numbers; |
| 15 | +// const numbers = [1, 2, 3, 4]; |
| 16 | +// const copiedNumbers = numbers; |
17 | 17 |
|
18 | 18 | // Using spread Opeator,
|
19 | 19 | // Also known as Shallow Cloning
|
20 | | -const newNumbers = [...numbers]; |
| 20 | +// const newNumbers = [...numbers]; |
21 | 21 |
|
22 | | -numbers.push(5); |
23 | | -console.log(numbers); // [ 1, 2, 3, 4, 5 ] |
24 | | -console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] |
25 | | -console.log(newNumbers); // [ 1, 2, 3, 4 ] |
| 22 | +// numbers.push(5); |
| 23 | +// console.log(numbers); // [ 1, 2, 3, 4, 5 ] |
| 24 | +// console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] |
| 25 | +// console.log(newNumbers); // [ 1, 2, 3, 4 ] |
| 26 | + |
| 27 | +// 2nd way : Array.slice() |
| 28 | +// const numbers = [1, 2, 3, 4]; |
| 29 | +// const copiedNumbers = numbers; |
| 30 | + |
| 31 | +// Using spread Opeator, |
| 32 | +// Also known as Shallow Cloning |
| 33 | +// const newNumbers = numbers.slice(); |
| 34 | + |
| 35 | +// numbers.push(5); |
| 36 | +// console.log(numbers); // [ 1, 2, 3, 4, 5 ] |
| 37 | +// console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] |
| 38 | +// console.log(newNumbers); // [ 1, 2, 3, 4 ] |
| 39 | + |
| 40 | +// Cloning Objects |
| 41 | +// 1st way : Spread Operator |
| 42 | +// const person = { name: "John", age: 22 }; |
| 43 | +// const newPerson = { ...person }; |
| 44 | + |
| 45 | +// person.age = 23; |
| 46 | +// console.log(person); // { name: 'John', age: 23 } |
| 47 | +// console.log(newPerson); // { name: 'John', age: 22 } |
| 48 | + |
| 49 | +// 2nd way : Object.assign() |
| 50 | +const person = { name: "John", age: 22 }; |
| 51 | +const newPerson = Object.assign({},person); |
| 52 | + |
| 53 | +person.age = 23; |
| 54 | +console.log(person); // { name: 'John', age: 23 } |
| 55 | +console.log(newPerson); // { name: 'John', age: 22 } |
0 commit comments