javascript 如何清空一个javascript数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3586158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to empty an javascript array?
提问by qinHaiXiang
var arr = [-3, -34, 1, 32, -100];
How can I remove all items and just leave an empty array?
如何删除所有项目并只留下一个空数组?
And is it a good idea to use this?
使用它是个好主意吗?
arr = [];
Thank you very much!
非常感谢你!
回答by John Kugelman
If there are no other references to that array, then just create a new empty array over top of the old one:
如果没有对该数组的其他引用,则只需在旧数组之上创建一个新的空数组:
array = [];
If you need to modify an existing array—if, for instance, there's a reference to that array stored elsewhere:
如果您需要修改现有数组——例如,如果有对该数组的引用存储在别处:
var array1 = [-3, -34, 1, 32, -100];
var array2 = array1;
// This.
array1.length = 0;
// Or this.
while (array1.length > 0) {
array1.pop();
}
// Now both are empty.
assert(array2.length == 0);
回答by a.boussema
the simple, easy and safe way to do it is :
简单、容易和安全的方法是:
arr.length = 0;
making a new instance of array, redirects the reference to one another new instance, but didn't free old one.
创建一个新的数组实例,将引用重定向到另一个新实例,但没有释放旧实例。
回答by Johannes Weiss
one of those two:
这两个之一:
var a = Array();
var a = [];
回答by BoltClock
Just as you say:
就像你说的:
arr = [];
回答by Stephen
Using arr = [];to empty the array is far more efficient than doing something like looping and unsetting each key, or unsetting and then recreating the object.
使用arr = [];清空数组比执行诸如循环和取消设置每个键,或取消设置然后重新创建对象之类的操作更有效。
回答by Stephen
Out of box idea:
开箱即用的想法:
while(arr.length) arr.pop();

