Home  >  Article  >  Web Front-end  >  Example JS deep copy operation of arrays and objects

Example JS deep copy operation of arrays and objects

coldplay.xixi
coldplay.xixiforward
2020-07-29 17:36:552384browse

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:

1. Deep copy of the array

let arr = [
 undefined,
 function(){
  console.log(123); 
 },
 true,
 null,
 {
  name:"123",
  age:23
 }
];
// arr作为拷贝对象

1. Array.from()

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 } ]

2. Object.assign()

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

3. Slice()

let arr1 = arr.slice(0);
arr[0] = 2;
console.log(arr1);
// [ undefined, [Function], true, null, { name: '123', age: 23 } ]

4 . Concat()

let arr1 = arr.concat();
arr[0] = 2;
console.log(arr1);
// [ undefined, [Function], true, null, { name: '123', age: 23 } ]

5. Extended operator deep copy

// 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

2. 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!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete