Javascript array length not changing - Stack Overflow

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

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?

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?

Share Improve this question edited Feb 24, 2024 at 19:10 Dharman 33.5k27 gold badges101 silver badges149 bronze badges asked Dec 12, 2010 at 21:00 dabdab 8271 gold badge12 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745182217a4615470.html

相关推荐

  • Javascript array length not changing - Stack Overflow

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

    13小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信