最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript array length not changing - Stack Overflow

programmeradmin0浏览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?

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);
}
发布评论

评论列表(0)

  1. 暂无评论