Way 1,splice
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
Other languages such as Java, whose array length is read-only, cannot be assigned a value. Such as
int[] ary = {1,2,3,4};
ary.length = 0;
Java will be an error, compile pass. And JS can, and empty the array,
var ary = [1,2,3,4];
ary.length = 0;
Console.log (ary); The output [], an empty array, is emptied
Mode 3, assigned to []
var ary = [1,2,3,4];
ary = []; Assignment to an empty array to empty the original array
In fact, it's not strictly a matter of emptying an array, just assigning the ary to an empty array, before the array will wait for garbage collection if no reference is directed at it.
Comparison Summary: Mode 2 Preserves 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:
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.