简体   繁体   English

如何清空一个javascript数组?

[英]How to empty an javascript array?

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!非常感谢!

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

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.创建一个新的数组实例,将引用重定向到另一个新实例,但没有释放旧实例。

one of those two:这两个之一:

var a = Array();
var a = [];

就像你说的:

arr = [];

Using arr = [];使用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.清空数组比执行诸如循环和取消设置每个键,或取消设置然后重新创建对象之类的操作要高效得多。

虽然您可以像其他一些答案一样将其设置为新数组,但我更喜欢使用clear()方法:

array.clear();

开箱即用的想法:

while(arr.length) arr.pop();

Ways to clean/empty an array清理/清空数组的方法

  1. This is perfect if you do not have any references from other places.如果您没有来自其他地方的任何参考,这是完美的。 (substitution with a new array) (用新数组替换)

arr = [] arr = []

  1. This Would not free up the objects in this array and may have memory implications.这不会释放此数组中的对象,并且可能会影响内存。 (setting prop length to 0) (将道具长度设置为 0)

arr.length = 0 arr.length = 0

  1. Remove all elements from an array and actually clean the original array.从数组中删除所有元素并实际清理原始数组。 (splicing the whole array) (拼接整个数组)

arr.splice(0,arr.length) arr.splice(0,arr.length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM