Way 1,splice
Copy Code code as follows:
var ary = [1,2,3,4];
Ary.splice (0,ary.length);
Console.log (ary); The output [], an empty array, is emptied
Method 2,length assignment to 0
This is interesting, and other languages such as Java, whose array length is read-only, cannot be assigned a value. Such as
Copy Code code as follows:
int[] ary = {1,2,3,4};
ary.length = 0;
Java will be an error, compile pass. And JS can, and empty the array,
Copy Code code as follows:
var ary = [1,2,3,4];
ary.length = 0;
Console.log (ary); The output [], an empty array, is emptied
The current prototype the array's clear and the empty of the array in the MooTools library use this way to empty the array.
Mode 3, assigned to []
Copy Code code as follows:
var ary = [1,2,3,4];
ary = []; Assignment to an empty array to empty the original array
Mode 2 preserves the other attributes of the array, and mode 3 is not retained. A lot of people think that Mode 2 is more efficient because it only assigns length to the value, and mode 3 builds the object again. The test is precisely the way 3 efficiency is high. Test code:
Copy Code code 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 can be seen: Mode 3 faster, more efficient. So if you don't keep the other attributes of the original array, the way you use it is more recommended.