Three methods for clearing arrays in JavaScript
Method 1, splice
123 |
var ary = [1,2,3,4]; ary.splice(0,ary.length); console.log(ary); // Output Array [0], empty Array, cleared |
Method 2. The value of length is 0.
This method is very interesting. For other languages such as Java, the length of the array is read-only and cannot be assigned a value. For example
12 |
int [] ary = { 1 , 2 , 3 , 4 }; ary.length = 0 ; |
An error will be reported in Java. In JS, yes, and the array is cleared,
123 |
var ary = [1,2,3,4]; ary.length = 0; console.log(ary); // Output [], empty array, which is cleared |
Currently, clear of the Prototype array and empty of the array in the mootools library use this method to clear the array.
Method 3: assign a value to []
12 |
var ary = [1,2,3,4]; ary = []; // Assign a value to an empty array to clear the original array. |
In fact, it cannot be said that the array is strictly cleared, but the array is re-assigned to an empty array. If the previous array is not referenced and pointed to it, it will wait for garbage collection.
Clear the Ext. CompositeElementLite class using this method.
Method 2 retains other attributes of the array, and method 3 does not. Many people think that method 2 is more efficient, because it only assigns a value to length, and method 3 creates an object again. It is tested that method 3 is highly efficient. Test code:
123456789 |
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:
The above results show that method 3 is faster and more efficient. Therefore, if you do not retain other attributes of the original array, Ext is more recommended.