js中清空一个数组
Ways to clear an existing array A
:
Method 1 所有清空方法中速度是最快的,但是实质是新建一个数组。原数组要是没有在别的地方引用或别的地方引用了但是不需要跟着原数组的数值改变而改变,就可以用这种方法
A =[];
// A = new Array();
This code will set the variable A
to a new empty array. This is perfect if you don't have references to the original array A
anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A
.
This is also the fastest solution
Method 2 empty原数组
A.length =0
This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of Javascript but it turns out that this is not the case. It also works when using "strict mode" in Ecmascript 5 because the length property of an array is a read/write property.
Method 3 empty原数组
A.splice(0,A.length)
Using .splice()
will work perfectly, but it's not very efficient because the .splice()
function will return an array with all the removed items, so it will actually return a copy of the original array in some (most?) Javascript implementations.
Method 4 是真正empty数组中最快的(不包括Method 1)
while(A.length >0){
A.pop();}
This solution is not very succinct but it is by far the fastest solution (apart from setting the array to a new array). If you care about performance, consider using this method to clear an array. Benchmarks show that this is at least 10 times faster than setting the length to 0 or using splice().
http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript