How do I overwrite (or unset and then set) an array? Seems like "array = new_array"
doesn't work.
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.
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);
Clearing an array
http://2ality.com/2012/12/clear-array.html
let myArray = [ 1, 2, 3, 4];
myArray = [];
myArray.length = 0;
myArray.length = 0
is what you're looking for! –
Deliquescence This should work.
array1 = array2;
If not, please provide more details.
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 = [];
Using Slice()
like this -> array = new_array.slice(0);
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.
© 2022 - 2024 — McMap. All rights reserved.
array = new_array
code is not working? – Deadline