I have this non associative array:
var cars = [ 'Lambo', 'Ferrari', 'Jeep' ];
I am trying to iterate throug the items:
for( var key in cars ){
alert( cars[key] );
}
But it does not work. It’s like the key
is not being recognized. The for
loop works with associative arrays but not with non associative. I am running out of ideas. How can I iterate through a non associative array in Java script?
Please don’t flag my questions. Let me know what is wrong and I will fix it as soon as possible.
2
Answers
use
of
instead ofin
in the for loophttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…of
Generally
for...in
is not recommended for arrays due to potential issues with unexpected prototype properties appearing in the loop.For iterating through a non-associative array in JavaScript, you can use various constructs. Here are a few options:
Using
forEach()
The
forEach()
method is available for arrays in JavaScript and is a concise way to iterate through each item in an array.Using
for...of
loopThe
for...of
loop is another clean way to iterate through the elements of an array.Using a
for
loop