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]?
仅有的幸福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()
PHP中文网2017-07-05 11:06:38
Copy array:
obj.a = arr.slice();
obj.a = JSON.parse(
JSON.stringify(arr)
);
巴扎黑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;
}
}
滿天的星座2017-07-05 11:06:38
If you are using ES2015, you can use the object spread operator to copy.
obj.a = [...arr]