Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array's length method

Can anyone explain why the second alert says 0 ?

  var pollData = new Array();
  pollData['pollType'] = 2;
  alert(pollData['pollType']); // This prints 2
  alert(pollData.length); // This prints 0 ??
like image 885
edwinNosh Avatar asked Dec 28 '22 23:12

edwinNosh


2 Answers

The length of the array is only changed when you add numeric indexes. For example,

pollData["randomString"] = 23;

has no effect on length, but

var pollData = [];
pollData["45"] = "Hello";
pollData.length; // 46

changes the length to 46. Note that it doesn't matter if the key was a number or a string, as long as it is a numeric integer.

Besides, you are not supposed to use arrays in this manner. Consider it more of a side effect, since arrays are objects too, and in JavaScript any object can hold arbitrary keys as strings.

like image 128
Anurag Avatar answered Dec 30 '22 13:12

Anurag


Because you haven't put anything into the array yet. You've only been assigning to a dynamically-created pollType attribute on the array object.

If you use numeric indices, then the array automagically takes care of length. For example:

var arr = [  ];    // same as new Array()
arr[2] = 'Banana!';
alert(arr.length);    // prints 3 (indexes 0 through 2 were created)
like image 24
Cameron Avatar answered Dec 30 '22 14:12

Cameron