Home > Article > Web Front-end > Example JS deep copy operation of arrays and objects
The example in this article describes the deep copy operation of JS arrays and objects. Share it with everyone for your reference, the details are as follows:
let arr = [ undefined, function(){ console.log(123); }, true, null, { name:"123", age:23 } ]; // arr作为拷贝对象
Array.from() can copy an The class array is converted into a real array, so it returns a new array.
let arr1 = Array.from(arr); arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
let arr1 = Object.assign([], arr) arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
This method can also be used as a deep copy of the object
let arr1 = arr.slice(0); arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
let arr1 = arr.concat(); arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
// let [...arr1] = arr; // 这两种都可以 let arr1 = [...arr]; arr[0] = 2; console.log(arr1); // [ undefined, [Function], true, null, { name: '123', age: 23 } ]
This method can also be used as a deep copy of an object
let obj = { name: "a", age: 20, sex: false, user: { a: 20, n: "b" }, f: function(){ return 1; }, u: undefined, n: null }
Use the spread operator and the Object.assign() method to deep copy objects
let obj1 = Object.assign({}, obj) obj[age] = 2; console.log(obj1); // let obj = { name: "a", age: 20, sex: false,user: {a: 20,n: "b},f: function(){return 1;},u: undefined,n: null}
Related learning recommendations: javascript video tutorial
The above is the detailed content of Example JS deep copy operation of arrays and objects. For more information, please follow other related articles on the PHP Chinese website!