31

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.

3
  • 8
    That is not a jQuery array. Commented Jul 18, 2012 at 14:25
  • implied facepalm. javascript is NOT jQuery.... Commented Jul 18, 2012 at 14:26
  • looks like this array is already cleared :) Commented Nov 9, 2016 at 3:26

4 Answers 4

37

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.

Sign up to request clarification or add additional context in comments.

5 Comments

not enough jQuery.
well he could always call it $myArray
@jAndy I don't think that you need jQuery for everything.....
@starbeamrainbowlabs - It was a joke, most likely a reference to this.
This does NOT empty an array. This just assigns NEW empty array to that variable. .length solution works fine, while this does not in this use-case: var obj = {arr: []}; var a = obj.arr; a.push('elem'); a.length = 0; console.log(obj); vs var obj = {arr: []}; var a = obj.arr; a.push('elem'); a = []; console.log(obj);
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 

Comments

2

To clear the array values you can do a simple:

myarray = []; 

P.s.

jQuery != javascript 

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.