62

I'm trying to empty an array containing my drawn coordinates when a button "clear" is pressed.

When I call drawnDivs.clear(), I get an error that it is not a function. drawnDivs is certainly an array, and I have Firebug console.logs printing things out. It's hosted here.

braX
  • 11,506
  • 5
  • 20
  • 33
Nona Urbiz
  • 4,873
  • 16
  • 57
  • 84

5 Answers5

81

Nope, it's not. But drawnDivs.length = 0 should work.

jordanbtucker
  • 5,768
  • 2
  • 30
  • 43
  • 1
    This will work if it's a true array, and not just an array-like object. – thomasrutter Oct 26 '10 at 03:54
  • 3
    @thomasrutter. True but it will preserve references and any other addition properties and functions defined on the array. – jordanbtucker Oct 26 '10 at 04:13
  • yes, this is still the best solution overall. And to be honest, it would still work on array-like objects, it just wouldn't free any of the existing members from memory right away. So only a minor point really. – thomasrutter Oct 26 '10 at 12:43
  • @thomasrutter -an "arraylike" object, is not an Array, to begin with - so...(?!) . – Bekim Bacaj Nov 10 '16 at 05:59
  • Objects that can be used as if they are arrays but which aren't arrays are fairly common in JavaScript. If you want your array handing code to work with "real" arrays as well as objects which can act as arrays, then you have to make sure it can cope with the latter. – thomasrutter Nov 11 '16 at 12:34
9

drawnDivs = [];

Mike Ruhlin
  • 3,546
  • 2
  • 21
  • 31
4

It was answered in Stack Overflow question How do I empty an array in JavaScript?.

Two examples from the answer:

var A = ['some', 'values', 'here'];

//Method 1

//(This was my original answer to the question)

A = [];




// Method 2 (as suggested by Matthew Crumley)

A.length = 0

And here is a nice write up on these two methods by Dr. Axel Rauschmayer.

Community
  • 1
  • 1
subhaze
  • 8,815
  • 2
  • 30
  • 33
  • The chosen answer in the referred link is not the right solution as it does not clear the variables that refer to the array being cleared. The correct answer in that thread is http://stackoverflow.com/a/8134354/206687 – Shamasis Bhattacharya Sep 26 '12 at 13:04
2

An optimized way to do it is:

while (arr.pop()) {}

See http://jsperf.com/kbk-clear-array/2.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

You could alternately use the Prototype library and then, use Prototype's clear() method.

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43