Three Ways to Empty Array in JavaScript

  • 2021-08-05 08:36:51
  • OfStack

Mode 1, splice


var ary = [1,2,3,4]; 
ary.splice(0,ary.length); 
console.log(ary); //  Output  [] Empty array, that is, it is emptied  

Mode 2, length is assigned to 0

This is an interesting way. In other languages, such as Java, the array of length is read-only and cannot be assigned a value. Such as


int[] ary = {1,2,3,4}; 
ary.length = 0; 

Errors will be reported in Java, and compilation will not pass.

In JS, the array can be emptied, such as


var ary = [1,2,3,4]; 
ary.length = 0; 
console.log(ary); //  Output  [] Empty array, that is, it is emptied  

Currently, the clear method for arrays in Prototype and the empty method for arrays in the mootools library use this method to empty arrays.

Mode 3, assign the value to []


var ary = [1,2,3,4]; 
ary = []; //  Assign value to 1 Empty arrays to empty the original array  

The clear method of the Ext. CompositeElementLite class of the Ext library is emptied in this way.

Mode 2 preserves other attributes of the array, while Mode 3 does not.

Many people think that Mode 2 is more efficient because it only re-assigns values to length, while Mode 3 re-creates an object. After testing, it is precisely the high efficiency of Mode 3. Test code:


var a = []; 
for (var i=0; i< 1000000; i++){ 
 a.push(i); 
} 
var start = new Date(); 
//a = []; 
a.length = 0; 
var end = new Date(); 
alert(end - start); 

Test results:

  IE6 IE7 IE8 IE9 Firefox Safari Chrome
a.length=0 94 29 14 1 4 3 1
a=[] 0 0 0 0 0 0 0

The above results can be seen: Mode 3 is faster and more efficient.

From the test results, if the other attributes of the original array Ext is not retained, it is more recommended.


Related articles: