search

Home  >  Q&A  >  body text

javascript - What is the use of clone method in js?

Sometimes when operating on arrays and the like, the clone method is used. I feel that it is okay to assign values ​​directly without using this. What are the benefits of doing so? To save memory? There are also shallow copies, deep copies, etc., forgive me for being a novice. .

大家讲道理大家讲道理2712 days ago788

reply all(3)I'll reply

  • typecho

    typecho2017-06-26 10:54:02

    The advantage is that unlike "=", the clone array is independent in memory, and you can do whatever you want with it.

    In js, arrays and objects are reference types.

    const arr = [1, 2, 3, 4, 5, 6];
    const arr1 = arr; // 直接赋值,arr1指向的是arr的内存,也就是说arr发生改变时,arr1也会被改变
    arr.push(123);
    console.log(arr1); // [1, 2, 3, 4, 5, 6, 123]
    
    const arr = [1, 2, 3, 4, 5, 6];
    const arr1 = arr.slice(0); // 克隆了一个arr1,arr与arr1指向不同的内存,arr的改变并不会影响到arr1
    arr.push(123);
    console.log(arr1); // [1, 2, 3, 4, 5, 6]
    

    So, the purpose of cloning is to generate a new copy of data without contaminating the original data.

    As for deep copy and shallow copy:

    const obj1 = {
        name: 'Ash',
        class: {
            a: 1,
            b: 2,
        }
    };
    
    // 浅拷贝
    const obj2 = {};
    for (let key in obj1) {
        obj2[key] = obj1[key];
    }
    
    // 深拷贝
    const copyObj = (obj) => {
        const newObj = {};
        for (let key in obj) {
            if (typeof obj[key] !== 'object') {
                newObj[key] = obj[key];
            } else {
                newObj[key] = copyObj(obj[key]);
            }
        }
        return newObj;
    }
    const obj3 = copyObj(obj1);
    
    obj1.name = 'Coco';
    obj1.class.a = 100;
    console.log(obj2.name, obj2.class.a); // Ash 100
    console.log(obj3.name, obj3.class.a); // Ash 1

    As you can see, the difference between shallow copy and deep copy is that shallow copy only traverses the first layer of obj1, and then assigns each attribute of obj1 to obj2; while deep copy does not, when the attribute value is an object At this time, the deep copy will create a new empty object, then assign the object's value to the empty object, and then return the empty object as the attribute of obj3.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-26 10:54:02

    A very important principle in JS programming is"Don't touch objects that are not yours"

    To give you a vivid metaphor, I lent you a book (object), and I thought you just wanted to read it (read), but you used it to practice calligraphy (write). I can’t even read the book when you return it to me. Normal content.

    And deepClone solves this problem. I give you a book, you go and copy it, return the book to me as is, and you can dispose of the copy as you wish.

    reply
    0
  • 阿神

    阿神2017-06-26 10:54:02

    Deep copy and shallow copy in javascript?

    reply
    0
  • Cancelreply