Copying depth is generally carried out for reference data type (data type: Object (Object), the array (Array), function (Function))
Shallow copy:
let obj = {id: 1, name: 2}; let newObj = obj; setTimeout(() => { newObj.id = 2; console.log(obj,newObj) },1000); // 输出如下 // { id: 2, name: 2 } { id: 2, name: 2 }We found that, with the change of newObj, obj also changes, which is obviously not what we want, the array is also true, then we need a deep copy.
Deep copy:
Method 1 (wrapper functions)
// constructor function of a deep copy function deepClone (obj) { var Result = Array.isArray (obj)? []: {}; // determine the current is passed in an array or an object for ( var Key in obj) { IF ( obj.hasOwnProperty (key)) {// if the key exists IF ( typeof obj [key] === 'Object' && obj [key]! == null ) {// obj [key] If object, recursively this method, obj [key] = arr || obj [key] = {} are 'Object' Result [Key] = deepClone (obj [Key]); } the else { Result [Key] = obj [Key]; } } } return result; }let arr1 = [1,2,3,4,5]; let arr2 = deepClone(arr1); arr2[0] = 'hello'; arr2[4] = 'world'; console.log(arr1); // [ 1, 2, 3, 4, 5 ] console.log(arr2); // [ 'hello', 2, 3, 4, 'world' ] let obj1 = {id: 1, name: 1, love: [1,2,3,4], test: {id: 1, name: 1}}; let obj2 = deepClone(obj1); obj2.love[0] = 'ecmascript'; obj2.test.id = 2; console.log(obj1); // { id: 1, name: 1, love: [ 1, 2, 3, 4 ], test: { id: 1, name: 1 } } console.log(obj2); // { id: 1,name: 1,love: [ 'ecmascript', 2, 3, 4 ],test: { id: 2, name: 1 } }Method 2 (JSON.parse and the JSON.stringify)
let obj1 = { id: 1, name: 1 }; let obj2 = JSON.parse(JSON.stringify(obj1)); obj2.id = 2; obj2.name = 2; console.log(obj1,obj2); // { id: 1, name: 1 } // { id: 2, name: 2 }Method 3 (In nodeJS projects, a lodash module, we can use it to provide a method to achieve a deep clone, or to download it locally, it is introduced into the corresponding file may be as follows js)
lodash Chinese network https://www.lodashjs.com/docs/latest
// npm install lodash -S const cloneDeep = require('lodash/cloneDeep') let arr3 = [1,2,3,4]; let arr4 = cloneDeep(arr3); arr4[1] = 'hello'; console.log(arr3,arr4); // [ 1, 2, 3, 4 ] // [ 1, 'hello', 3, 4 ]
javascript realize the depth of copies
Guess you like
Origin www.cnblogs.com/troublehuan/p/12029129.html
Ranking