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]?
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:
delete arr
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)
arr
concat
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()
Copy array:
obj.a = arr.slice();
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]
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)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()
Copy array:
Use slices
Utilize JSON
I don’t understand what you mean by destroying it. . . .
As for deep copy:
If you are using ES2015, you can use the object spread operator to copy.