Javascript array length not changing
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 und开发者_开发问答erstanding about these arrays?
Thanks for your time! :+D
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
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);
}
精彩评论