-2

Even though we can use array.length to get array length it may go wrong in a case like below..

var a = [2, 4, "bang", undefined, NaN, 5]; 
a.length = 0; 
document.write(a.length);  

counting with for in may also go wrong if the array has additional properties defined.

So is there a way to get array length dynamically?

Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40

3 Answers3

2

Calling

a.length = 0;

Does remove all elements from the array

console.log(a[2]) // undefined

Therefore, your array no longer contains any elements.

Also remember that setting properties that are not coercible to an integer (a.something = 'blah') will not affect the length property.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

If you do, a.length = 0, It will remove all array elements, and the length will be 0. Does it show any other value?

dr_dev
  • 492
  • 3
  • 17
1

a.length is always correct. a.length = 0; TRUNCATES all data from array.

Ginden
  • 5,149
  • 34
  • 68