edwinNosh
edwinNosh

Reputation: 399

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 ??

Upvotes: 4

Views: 4771

Answers (6)

matt oconnell
matt oconnell

Reputation: 1

var pollData = Array();

function test() {
    pollData[0] = 2
    alert(pollData[0]);
    alert(pollData.length);
}

//[x] is the array position; hence ['polltype'] is causing issues

Upvotes: 0

Jasuten
Jasuten

Reputation: 1570

array.length returns how many values are stored in the array. The first alert is returning the value of the position 'pollType'.

The reference guide I always use when needing help with javascript arrays is this page http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

I'd also read what it says under the heading Javascript Does Not Support Associative Arrays, as you may run into problems with this also.

Upvotes: 0

alex
alex

Reputation: 490233

Arrays in JavaScript have numeric indexes only.

Use an object, which is essentially what you are doing above, setting properties on that array object.

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185933

The length property takes into consideration only those members of the array which names are indexes (like '1', '2', '3', ... ).

Upvotes: 0

Cameron
Cameron

Reputation: 98746

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)

Upvotes: 2

Anurag
Anurag

Reputation: 141879

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.

Upvotes: 8

Related Questions