开发者

How to empty an javascript array?

开发者 https://www.devze.com 2023-01-13 04:03 出处:网络
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?
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 = [];


Just as you say:

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.


Out of box idea:

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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号