views:

306

answers:

5

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

Thank you in advance.

A: 

Have you tried assigning the array to null and then to a new array?

Evan
+9  A: 

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

array = new Array();

Or you can use an empty array literal:

array = [];

If you have several references to one array so that you have to empty the actual array object rather than replacing the reference to it, you can do like this:

array.splice(0, array.length);
Guffa
A: 

I'm not exactly sure what you're trying to do, but there are a couple of ways to go about resetting an array.

You could just iterate through the existing array and set each index equal to null (or an empty string or 0 or whatever value you consider to be a reset):

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

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

arr = [];
Tom
A: 

This should work.

array1 = array2;

If not, please provide more details.

Andrejs Cainikovs
I don't think you need to explicitly state array1 = null. If you just update the reference, the garbage collector should recognize an instance that has no references pointing to it.
Tom
No need for two assignments; the second one is enough.
JW
Yes, you are correct.
Andrejs Cainikovs
A: 

Hm, it seems like the problem wasn't what I thought; my mistake was the following rows, which after all havn't got anything 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 was ment to remain static in the sms.original object, 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 for bothering you, I should have elaborated but the code is splited in multiple files and functions. Thank you guys anyway, now does Guffa's splice technique work for me.

Ivarska