Is there a way to empty an array and if so possibly with .remove()
?
For instance,
A = [1,2,3,4];
How can I empty that?
Is there a way to empty an array and if so possibly with For instance,
How can I empty that? |
||||
add comment |
Very simple:
EDIT A little extra explanation is required here. The code above However (as other have pointed out below) if you have references to this array, you can empty the original array by setting its length to 0 or by calling Setting the length to zero is the most efficient solution, but this could create problems in some implementations of Javascript (although I don't know of any). Using So the preferred way to clear an existing array is:
(Matthew Crumley's answer to this question is probably the best one) | |||||||||||||||||||||
|
How about the below modified version of Jan's initial suggestion?
| |||
|
According to jsperf a fast solution would be to pop/shift each Array Element in a for-loop.
For reference: Link obsolete. See below. Edit: The solution was incorrect. Please refer to the solution of tanguy_k for the fastest and correct way to empty an array. | |||||||||||||
|
Answers from Jan and David McCurley are incorrect! As noted by 755 in a comment, the algorithm provided by Jan only removes half of the items from the array. Here the fastest working implementation (while keeping the same array):
And the test that goes with it:
Here the updated jsPerf: http://jsperf.com/array-destroy/32 | |||||||||||||||||||||
|
The fastest solution for all current browsers is to implement the pop or shift method. Combining answers from 'leech' and 'jan', we can come up with a method that is declared once and makes it easy to clear the array:
| |||||||||
|
The simplest way to delete all content of Array is to set length to zero. Eg. var myArray = ['A','B','C'];
| |||||
|
and call it: =) | |||||||||
|
You can add this to your JavaScript file to allow your arrays to be "cleared":
| |||||
|
A more cross-browser friendly and more optimal solution will be to use the
| |||||||||||||||||||||
|
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:
| |||||||||||||||||||||
|
A = []
method before finding this thread, but I almost continued doing my normal thing until I saw @Daniel's highly rated comment on the currently accepted answer – phatskat Jan 19 at 21:01