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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With