Way 1,splice
1 2 3 |
var ary = [1,2,3,4]; ary.splice(0,ary.length); console.log(ary); // 输出 Array[0],空数组,即被清空了 |
Method 2,length is assigned a value of 0
This is interesting, and other languages such as Java, whose array length is read-only, cannot be assigned a value. Such as
0 S |
int [] ary = { 1 , 2 , 3 , 4 }; ary.length = 0 ; |
Java will error, compile pass. And JS can be, and the array is emptied,
1 2 3 |
var ary = [1,2,3,4]; ary.length = 0; console.log(ary); // 输出 [],空数组,即被清空了 |
The current prototype array in the clear and MooTools libraries in the empty array is used this way to empty the array.
Mode 3, assigned to []
1 2 |
var ary = [1,2,3,4]; ary = []; // 赋值为一个空数组以达到清空原数组 |
In fact, this is not a strict meaning of the empty array, just the ARY is re-assigned to an empty array, before the array if there is no reference to it will wait for garbage collection.
The clear of the EXT library Ext.compositeelementlite class is cleared using this method.
Mode 2 retains the other properties of the array, and mode 3 is not preserved. Many people think that Mode 2 is more efficient because it simply re-assigns a value to length, and mode 3 re-establishes the object. The test is precisely the efficiency of mode 3. Test code:
1 2 3 4 5 6 7 8 9 |
var
a = []; for
(
var
i=0; i< 1000000; i++){
a.push(i);
} var start = &NBSP; new date (); //a = []; a.length = 0; var end = &NBSP; new date (); alert (end-start); |
Test results:
The above results can be seen: 3 faster and more efficient. Therefore, if you do not preserve the other properties of the original array, the method of ext is more recommendable.
Turn from:
Http://www.2cto.com/kf/201409/335383.html
To delete an item or items in an array: http://www.cnblogs.com/Joans/p/3981122.html
Turn: JS empty array