javascript - js object deep copy and assignment
扔个三星炸死你
扔个三星炸死你 2017-07-05 11:04:38
0
4
951

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

扔个三星炸死你
扔个三星炸死你

reply all(4)
仅有的幸福

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()

Ty80

Copy array:

Use slices

obj.a = arr.slice(); 

Utilize JSON

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

巴扎黑

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;
    }
}
滿天的星座

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

obj.a = [...arr]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template