File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes HTML, CSS and JavaScript and the fly likes Iterating keys of JavaScript Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Iterating keys of JavaScript Array" Watch "Iterating keys of JavaScript Array" New topic
Author

Iterating keys of JavaScript Array

Susan Smith
Ranch Hand

Joined: Oct 13, 2007
Posts: 224
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

Joined: Jan 10, 2002
Posts: 61092
    
  66

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 ]

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Susan Smith
Ranch Hand

Joined: Oct 13, 2007
Posts: 224
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

Joined: Jan 10, 2002
Posts: 61092
    
  66

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

Joined: Oct 13, 2007
Posts: 224
I see. Thanks Bear.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Iterating keys of JavaScript Array