JS shallow copy & deep copy

来源

Arrays are Reference Types

  • Copying a Value type
let value = 3;
let valueCopy = value; // create copy

console.log(valueCopy); // 3

// Change valueCopy
valueCopy = 100
console.log(valueCopy); // 100

// ✅ Original NOT affected 
console.log(value); // 3


  • Copying a Reference type
let array = [1,2,3];
let arrayCopy = array; // create copy

console.log(arrayCopy); // [1,2,3];

// Change 1st element of the array
arrayCopy[0] = '👻';
console.log(arrayCopy); // [ '👻', 2, 3 ]

// ❌Original got affected
console.log(array); // [ '👻', 2, 3 ]



Solutions:

  • let arrayCopy = [...array] (Shallow copy)
  • let copyArr = arr.slice()
  • let copyArr = Object.assign([], arr)
    ✅Works for one-dimensioned array.
    ❌Won't work for nested array.
  1. let arrayCopy = JSON.parse(JSON.stringify(nestedArray));(Deep copy)
    ✅ Only work with Number and String and Object literal without function or Symbol properties.
    ❌ Function or Symbol properties ( values not compatible with JSON )

  2. deepclone
    ✅work with all types, function and Symbol are copied by reference.

const lodashClonedeep = require("lodash.clonedeep");

const arrOfFunction = [() => 2, {
    test: () => 3,
}, Symbol('4')];

// deepClone copy by refence function and Symbol
console.log(lodashClonedeep(arrOfFunction));
// JSON replace function with null and function in object with undefined
console.log(JSON.parse(JSON.stringify(arrOfFunction)));

// function and symbol are copied by reference in deepClone
console.log(lodashClonedeep(arrOfFunction)[0] === lodashClonedeep(arrOfFunction)[0]);
console.log(lodashClonedeep(arrOfFunction)[2] === lodashClonedeep(arrOfFunction)[2]);
  1. Using Recursion
const clone = (items) => items.map(item => Array.isArray(item) ? clone(item) : item);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容