Overwrite array in JavaScript

我只是一个虾纸丫 提交于 2019-12-06 07:03:28

问题


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


回答1:


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);



回答2:


This should work.

array1 = array2;

If not, please provide more details.




回答3:


Clearing an array

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

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

myArray = [];
myArray.length = 0;



回答4:


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 = [];



回答5:


Using Slice()

like this -> array = new_array.slice(0);




回答6:


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.



来源:https://stackoverflow.com/questions/1555675/overwrite-array-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!