简体   繁体   中英

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

  1. This Would not free up the objects in this array and may have memory implications. (setting prop length to 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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