0

I've got an array of an object, that doesn't seem to update in length. What am I not knowing about Javascript arrays?

http://stackoverflow.pastebin.com/aqZtRkkf

The length is reported as 0, and it shows the array as empty, but a console.log shows it as having the array indices!

What am I not understanding about these arrays?

Thanks for your time! :+D

dab
  • 817
  • 1
  • 12
  • 23

2 Answers2

6
  this.Hats[ "Red" ] = new Hat( oPar, "red" )
  this.Hats[ "Yellow" ] = new Hat( oPar, "yellow" );

This is where your problem is. You aren't using the array as an array, you're just using it as an object, setting the properties Hats.Red and Hats.Yellow instead of filling the array indexes.

Try this:

  this.Hats.push( new Hat( oPar, "red" ) );
  this.Hats.push( new Hat( oPar, "yellow" ) );

The push function in javascript

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
  • Thanks, is there no way to use a string as the Array index however? – dab Dec 12 '10 at 21:08
  • You can use an array as a dictionary by assigning items with string indexes. It will not affect the length property of the array, but you can get the length of all the dictionary keys using one of these methods. http://stackoverflow.com/questions/5223/length-of-javascript-associative-array – Gordon Gustafson Dec 12 '10 at 21:13
  • If you're going to do this, you shouldn't even use an Array ([])... just use an Object ({}). JavaScript Objects are dictionaries. You don't get array methods with them, but you get string keys. This sounds like what you want. – Zach Dec 12 '10 at 21:30
  • haha, turns out my real issue was something completely unrelated. Thanks everyone :) – dab Dec 13 '10 at 02:12
  • @dab what was the real issue then? We want to hear about it. :D – Gordon Gustafson Dec 13 '10 at 13:30
  • 1
    Turned out my indices were including a newline in some of the instances, so when attempting to get the key w/o the newline, it wouldn't match that array index. However I ended up using the information from this regardless :) – dab Dec 18 '10 at 08:54
1

You're using an associative array. This type of array allows you to define a key for each array member. Using an array this way means that there is no index value upon which you can traverse the members, instead you can use for (var i in object).

for (var key in test.People["Fred"].Hats) {
    console.log(key);
}
Jonathan
  • 5,953
  • 1
  • 26
  • 35