search

Home  >  Q&A  >  body text

javascript - js object deep copy and assignment

In the code, we get an array arr=[1,2,3];
Because it will be destroyed immediately, it cannot be directly assigned to the object Obj.a.
How to write jquery in this case to make arr After destruction Obj.a=[1,2,3]?

扔个三星炸死你扔个三星炸死你2732 days ago955

reply all(4)I'll reply

  • 仅有的幸福

    仅有的幸福2017-07-05 11:06:38

    In general, it is rare to encounter "destroy" in JS. Then, I don't understand what you mean by immediate destruction?

    If it refers to delete arr, then there will be no problem with direct assignment, as shown below:

    If you want to change the content of arr. Then you can copy an array (there are several methods, concat is just one of them)

    Obj.a = [].concat(arr);

    If you really need deep copy, jQuery.fn.clone(), but it seems to have some restrictions.

    For other data, it is still a bit difficult and troublesome to write a deep copy yourself. It is better to use Lodash's cloneDeep()

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 11:06:38

    Copy array:

    Use slices

    obj.a = arr.slice(); 

    Utilize JSON

    obj.a = JSON.parse(
        JSON.stringify(arr)
    ); 

    reply
    0
  • 巴扎黑

    巴扎黑2017-07-05 11:06:38

    I don’t understand what you mean by destroying it. . . .
    As for deep copy:

    function cloneObj(obj){
        if( !obj || typeof obj == "string" ){
            return obj;
        } else if ( obj instanceof Array ){
            return [].concat(obj);
        } else {
            var tempObj = {};
            for( var key in obj ){
                tempObj[key] = cloneObj(obj[key]);
            }
            return tempObj;
        }
    }

    reply
    0
  • 滿天的星座

    滿天的星座2017-07-05 11:06:38

    If you are using ES2015, you can use the object spread operator to copy.

    obj.a = [...arr]

    reply
    0
  • Cancelreply