Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for( … in …) not working with array

Tags:

javascript

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
like image 723
Lenar Hoyt Avatar asked Aug 25 '11 12:08

Lenar Hoyt


People also ask

Can we use for in for array?

Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop. for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.

Why we should not use for in with array?

for…in is not intended to iterate over arrays in the usual sense. So in most cases, it is the wrong tool. However, there might be rare situations where it is a good idea to use it for that purpose. Just do it consciously and be aware of the exact behavior so you don't introduce any bugs into your code.

What is the correct way to write a JavaScript array?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


1 Answers

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.

like image 140
Jamiec Avatar answered Sep 29 '22 21:09

Jamiec