JavaScript: overwrite array

How do I overwrite (or delete and then set) an array? It seems like "array = new_array" doesn't work.

Thanks in advance.

+2


source to share


5 answers


Hm, it looks like the problem is not what I thought; my mistake was the following lines, which in the end had nothing to do with arrays at all:

sms.original = eval('(' + data + ')');
sms.messages = sms.original;

      

sms.original becomes an object and then sms.messages becomes sms.original (I just wanted them to have the same value). The objects contain an array named items which should remain static in sms.original, but when I changed sms.messages the original object changed as well. The solution was simple:



sms.original = eval('(' + data + ')');
sms.messages = eval('(' + data + ')');

      

Sorry to bother you, I had to develop, but the code is split into multiple files and functions. Thank you guys, anyway, Guffa welding technique now works for me.

-1


source


To create an empty array to assign to a variable, you can use the Array constructor:

array = new Array();

      

Or you can use an empty array literal:



array = [];

      

If you have multiple references to the same array so that you can clear the actual array object rather than replace the reference to it, you can do the following:

array.splice(0, array.length);

      

+12


source


This should work.

array1 = array2;

      

If not, please provide more details.

+1


source


I'm not really sure what you are trying to do, but there are several ways to reload the array.

You can just loop over the existing array and set each index to null (or an empty string, or 0, or whatever value you think is reset):

for(var i = 0; i < arr.length; i++) {
   arr[i] = null;
}

      

You can also just update the existing reference to a new instance of the object:

arr = [];

      

0


source


Clearing an array

http://2ality.com/2012/12/clear-array.html

let myArray = [ 1, 2, 3, 4];

myArray = [];
myArray.length = 0;

      

0


source







All Articles