• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterating keys of JavaScript Array

 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I'm wondering if I have a JAVASCRIPT array like this below, how do I iterate the keys of the array and/ or iterate the array itself using for loop??



Thanks in advance for the help.
[ February 15, 2008: Message edited by: Bear Bibeault ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65217
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not an array. It's merely a JavaScript Object instance. Don't confuse the properties of objects with Array indexes. Just because they both use the [] operators does not make them the same thing. Of course the fact that Arrays themselves are Objects that can have both indexes and properties makes this very confusing.

But, to answer your question:

will iterate over all properties of v and set the property name as p within the loop.
[ February 15, 2008: Message edited by: Bear Bibeault ]
 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see. Now I'm confused why when I want to build the data structure, it stops at alert message "point A" and it doesn't continue to the next alert.

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65217
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because you haven't created a JavaScirpt object.

When you declare a variable as such:You have created a variable with undefined contents.

You then attempted:which tried to created a property named A on undefined content. No can do.

Rather, you need to create a JavaScript object. Consider:or its more grown-up shortcut:

Now, test points to an empty Javascript object ready to to be assigned new properties.

By the way, when defining properties such as A, which are valid identifiers, it's good practice to use the simpler dot notation rather than the general [] notation: They are completely equivalent.
[ February 19, 2008: Message edited by: Bear Bibeault ]
 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see. Thanks Bear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic