For (... in ...) does not work with an array

I'm somehow confused:

I have a list of such commands:

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

If I try to access one of these commands, how 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
+5
source share
6 answers

Why use for..inwith an array? Just access by index, and also avoid potential problems with prototype expansion (see hasOwnProperty)

var i,len=commands.length;

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

If order doesn't matter more briefly

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

}

or

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

for iterates the array in javascript, so you want:

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

those. the variable commandin your example is the index of the array, not the enumerated element from the array.

+6
source

for ... in , . :

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

:

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

The design is for (.. in ..)designed to iterate over objects, not arrays. Since you have an array of objects, you should do:

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

For a detailed explanation of why you should use this construct forinstead for...in, see answer # 3010848 .

+2
source

You tried:

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

All Articles