Method 1, splice
var ary = [1,2, 3,4];
ary.splice(0,ary.length);
console.log(ary); // Output [], empty array, that is, cleared
Method 2, assign length to 0
This method is very interesting. In other languages such as Java, the length of the array is read-only and cannot be assigned. For example,
int[] ary = {1,2,3 ,4};
ary.length = 0;
An error will be reported in Java and the compilation will not pass. In JS, it is possible, and the array is cleared,
var ary = [1,2,3,4];
ary.length = 0;
console.log(ary); // Output [], empty array, that is, cleared
Currently,
clear for arrays in Prototype and
empty for arrays in the mootools library use this method to clear arrays.
Method 3, assignment is []
var ary = [1,2,3,4];
ary = []; // Assign an empty array to clear the original array
Method 2 retains other attributes of the array, method 3 is not retained. Many people think that method 2 is more efficient because it only reassigns length, while method 3 re-creates an object. After testing, it is precisely method 3 that is most efficient. 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:
As you can see from the above results: Method 3 is faster and more efficient. Therefore, if the other attributes of the original array are not retained, the method used by Ext is more recommended.