const arr1 = [1, 2, 3]; const arr2 = arr1; arr1[0] = 4; console.log(arr2); // [ 4, 2, 3 ]
const arr1 = [1, 2, ["a", "b", "c"]]; const arr2 = arr1.slice(); arr1[0] = 3; console.log(arr2); // [ 1, 2, [ 'a', 'b', 'c' ] ] arr1[2][0] = "d"; console.log(arr2); // [ 1, 2, [ 'd', 'b', 'c' ] ]
const arr1 = [1, 2, ["a", "b", "c"]]; const arr2 = [].concat(arr1); arr1[0] = 3; console.log(arr2); // [ 1, 2, [ 'a', 'b', 'c' ] ] arr1[2][0] = "d"; console.log(arr2); // [ 1, 2, [ 'd', 'b', 'c' ] ]
const arr1 = [1, 2, ["a", "b", "c"]]; const arr2 = Array.from(arr1); arr1[0] = 3; console.log(arr2); // [ 1, 2, [ 'a', 'b', 'c' ] ] arr1[2][0] = "d"; console.log(arr2); // [ 1, 2, [ 'd', 'b', 'c' ] ]
const arr1 = [1, 2, ["a", "b", "c"]]; const arr2 = [...arr1]; arr1[0] = 3; console.log(arr2); // [ 1, 2, [ 'a', 'b', 'c' ] ] arr1[2][0] = "d"; console.log(arr2); // [ 1, 2, [ 'd', 'b', 'c' ] ]
const obj1 = { a: 1, b: { c: 1, d: 2 } }; const obj2 = Object.assign({}, obj1); obj1.a = 3; console.log(obj2); // { a: 1, b: { c: 1, d: 2 } } obj1.b.c = 3; console.log(obj2); // { a: 1, b: { c: 3, d: 2 } }
const obj1 = { a: 1, b: { c: 1, d: 2 } }; const obj2 = { ...obj1 }; obj1.a = 3; console.log(obj2); // { a: 1, b: { c: 1, d: 2 } } obj1.b.c = 3; console.log(obj2); // { a: 1, b: { c: 3, d: 2 } }
const obj1 = { a: 1, b: { c: 1, d: 2 } }; const copyObj = (obj) => { const copiedObj = {}; for (let key in obj) { if (typeof obj[key] === "object") { copiedObj[key] = copyObj(obj[key]); } else { copiedObj[key] = obj[key]; } } return copiedObj; }; const obj2 = copyObj(obj1); obj1.b.c = 3; console.log(obj2); // { a: 1, b: { c: 1, d: 2 } }
const arr1 = [1, 2, [1, 2, 3]]; const arr2 = JSON.parse(JSON.stringify(arr1)); arr1[2][0] = 200; console.log(arr2); // [ 1, 2, [ 1, 2, 3 ] ]
const _ = require("lodash"); const obj1 = { a: 1, b: { c: 2 } }; const obj2 = _.cloneDeep(obj1); obj1.b.c = 300; console.log(obj2); // { a: 1, b: { c: 2 } }