admin管理员组

文章数量:1180493

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!

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!

Share Improve this question edited Aug 27, 2010 at 16:18 John Kugelman 361k69 gold badges547 silver badges594 bronze badges asked Aug 27, 2010 at 16:16 qinHaiXiangqinHaiXiang 6,41912 gold badges48 silver badges61 bronze badges 3
  • 4 You answered your own question, at least the first one! – Stephen Commented Aug 27, 2010 at 16:17
  • possible duplicate of How to empty an array in JavaScript? – Abid Rahman K Commented Apr 25, 2013 at 17:54
  • 2 Possible duplicate of How do I empty an array in JavaScript? – Mohammad Usman Commented Nov 16, 2017 at 8:06
Add a comment  | 

8 Answers 8

Reset to default 21

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.

These are the ways to empty an array in JavaScript

  1. arr = [];
  2. arr.splice(0, arr.length);
  3. arr.length = 0;

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)

本文标签: How to empty an javascript arrayStack Overflow