There are three methods for clearing arrays in JavaScript. For more information, see. Method 1, splice
The Code is as follows:
Var ary = [1, 2, 4];
Ary. splice (0, ary. length );
Console. log (ary); // output [], empty array, which is 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
The Code is as follows:
Int [] ary = {1, 2, 4 };
Ary. length = 0;
An error will be reported in Java. In JS, yes, and the array is cleared,
The Code is as follows:
Var ary = [1, 2, 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 []
The Code is as follows:
Var ary = [1, 2, 4];
Ary = []; // assign a value to an empty array to clear the original array.
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:
The Code is as follows:
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.