Dave's Brain

Browse - Programming Tips - How to I enumerate everything in a javaScript array?

Date: 2010jul19
Updated: 2017jun8
Language: javaScript
Level: beginner
Keywords: loop

Q.  How to I enumerate everything in a javaScript array?

A.  If it is NOT an associative array use a for-loop like this:

var a = [ 'apple', 'ibm', 'microsoft' ];
I prefer this way:
for (var i in a) { var element = a[i]; // Do something with element }
This works because a is actually:
var a = { 0: 'apple', 1: 'ibm', 2: 'microsoft' };
The conventional way:
for (var i = 0; i < a.length; i++) { var element = a[i]; // Do something with element }
ECMASscript 2015 introduced "of" which is nice, but can't be relied on:
for (let element of a) { // Do something with element }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.