The method of vue js object copy is simple and easy to use

The method of object copy is a difficult point, especially deep copy. It is recommended to run the code to help understand the copy.

1. json method

  1. Suitable situation:
     Deep clone of JSON object. The method is to first convert JSON.stringify() to a json string, and then JSON.parse() to a json array

  2. Disadvantages:
      a. If there are functions in your object, the function cannot be copied.
      b. The properties and methods on the prototype chain of the copyObj object cannot be copied .

var obj = {
    
    
    x: 1,
    y: {
    
    
        a: 1,
        b: 0,
        c: [1, 2, 3]
    }
};

// 相同的引用
var obj2 = obj;
console.log(obj2 == obj); //true 直接复制只是复制对象的指针,还指向同一个对象

//不同的引用
var obj3 = JSON.parse(JSON.stringify(obj));
console.log(obj3 == obj) //false  通过json方法复制后的地址不一样
console.log(obj3);

Front-end interview questions (1000+) scan the code to view

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/110240797