Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating through a non-associative array in Java script

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please don’t flag my questions. Let me know what is wrong and I will fix it as soon as possible.

>Solution :

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]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading