Ways to clear an existing array A. (From Stack Overflow)

1 Method 1

(this was my original answer to the question)

A = [];

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.

2 Method 2 (as suggested by Matthew Crumley)

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.

3 Method 3 (as suggested by Anthony)

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.

4 Method 4 (as suggested by tanguyk)

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().



blog comments powered by Disqus

Published

06 January 2015

Category

HTML5

Tags