Lenar Hoyt
Lenar Hoyt

Reputation: 6159

for( … in …) not working with array

I'm somehow confused:

I have a list of commands like this:

var commands = [{"command": "read"}, {"command": "write"}, {"command": "login"}];

If I try it access one of the commands like this it works:

console.log(commands[0]["command"]); // Output is "read"
console.log(commands[0].command);    // Output is "read"

But if I try this the output is always undefined:

for(command in commands)
    console.log(command["command"]); // undefined, undefined, undefined

Upvotes: 9

Views: 4130

Answers (6)

James Sumners
James Sumners

Reputation: 14785

The for (.. in ..) construct is for looping over objects, not arrays. Since you have an array of objects, you should be doing:

for (var i = 0, j = commands.length; i < j; i += 1) {
  console.log(commands[i].command);
}

For a thorough explanation as to why you should use this for construct instead of the for...in, see answer #3010848.

Upvotes: 3

Jamie Treworgy
Jamie Treworgy

Reputation: 24344

Why use for..in with an array? Just access by index, and you also avoid potential problems of prototype extensions (see hasOwnProperty)

var i,len=commands.length;

for (i=0;i<len;i++ ) {
    console.log commands[i].command
}

If order does not matter, more concisely

for (i=commands.length-1;i>=0;i-- ) {

}

Or

var i=commands.length;
while (i--) {
   ...
}

Upvotes: 2

Jon
Jon

Reputation: 437574

The for ... in construct iterates over the keys of the objects in the array, not the objects themselves. So you would need to write:

for(index in commands)
    console.log(commands[index]["command"]);

Upvotes: 10

Seth
Seth

Reputation: 6260

Have you tried:

for(command in commands[0]) {
    console.log(command["command"]);
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136154

for does an array iteration in javascript, so you want:

for(command in commands)
    console.log(commands[command]["command"]);

ie, the command variable in your example is an array index, not the enumerated item from the array.

Upvotes: 9

m0sa
m0sa

Reputation: 10940

Use it like this

 for(var x in commands)
      console.log(commands[x].command);

Upvotes: 2

Related Questions