Home > Web Front-end > JS Tutorial > body text

Example JS deep copy operation of arrays and objects

coldplay.xixi
Release: 2020-07-29 17:36:55
forward
2366 people have browsed it

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作为拷贝对象
Copy after login

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 } ]
Copy after login

2. Object.assign()

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

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 } ]
Copy after login

4 . Concat()

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

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 } ]
Copy after login

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
}
Copy after login

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}
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!