27

Possible Duplicate:
how to empty an array in JavaScript

How to remove all items from jQuery array?

I have array var myArray = [];, I want to clear all items in this array on every post back.

Community
  • 1
  • 1
Ranjith
  • 531
  • 3
  • 10
  • 20

5 Answers5

35

Simplest thing to do is just

myArray = [];

again.

edit — as pointed out in the comments, and in answers to other questions, another "simplest thing" is

myArray.length = 0;

and that has the advantage of retaining the same array object.

Pointy
  • 389,373
  • 58
  • 564
  • 602
10

you can remove all item in myArray using array length, it's common pattern.

try this

var myArray = [1, 2, 3];    
myArray.length = 0; // remove all item
blueiur
  • 1,407
  • 1
  • 11
  • 17
1

There is no such thing as a jQuery array, that's just a javascript array. When a page posts back, it re-renders and all of the javascript is re-run, you don't need to clear the contents of the array.

if, during execution of the page, you wanted to clear a javascript array, just re-initialize it as a new, blank array:

myArray = []; // no var, we are just initializing not declaring
jbabey
  • 44,525
  • 12
  • 67
  • 94
1

To clear the array values you can do a simple:

myarray = [];

P.s.

jQuery != javascript
Anik Islam Abhi
  • 24,762
  • 8
  • 55
  • 78
napolux
  • 14,547
  • 9
  • 50
  • 69
0

Here is a list of methods you can do on an Array in javascript

Evan Larsen
  • 9,817
  • 4
  • 44
  • 60