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.
CodePudding user response:
use of
instead of in
in the for loop
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
CodePudding user response:
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.
var cars = ['Lambo', 'Ferrari', 'Jeep'];
cars.forEach(function(car) {
console.log(car);
});
Using for...of
loop
The for...of
loop is another clean way to iterate through the elements of an array.
var cars = ['Lambo', 'Ferrari', 'Jeep'];
for (let car of cars) {
console.log(car);
}
Using a for
loop
var cars = ['Lambo', 'Ferrari', 'Jeep'];
for (var i = 0; i < cars.length; i ) {
console.log(cars[i]);
}