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?

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

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?

2 Answers 2

5
  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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, is there no way to use a string as the Array index however?
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. stackoverflow.com/questions/5223/…
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.
haha, turns out my real issue was something completely unrelated. Thanks everyone :)
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 :)
|
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.