If there is an array, is it possible to empty with .remove()?
For instance,
A = [1,2,3,4];
How can I empty that?
If there is an array, is it possible to empty with .remove()? For instance,
How can I empty that? |
||||
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) |
|||||||||||||||||||||
|
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 more cross-browser friendly and more optimal solution will be to use the
|
|||||||||||||||||
|
You can add this to your JavaScript file to allow your arrays to be "cleared":
|
|||
|
and call it: =) |
|||
|
According to jsperf the fastest solution would be to pop/shift each Array Element in a for-loop.
For reference: http://jsperf.com/array-destroy/11 |
|||
|
Based on http://jsperf.com/array-destroy it looks like setting array.length is not the high performance solution to emptying an array, regardless of other factors. Instead
appears to be the more efficient solution. |
|||
|
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