2

How to loop through a fixed (development time) list of values in JavaScript?

In Perl, I'd do:

for my $item ('foo', 'bar', 'baz') {

which would run the loop with foo, bar and baz in $item (one each loop run).

JavaScript could do:

for (item in new Array('foo', 'bar', 'baz')) {

but that would make item contain 0, 1 and 2, not the values.

Copy&paste the source for each item would be an option, but a very bad one in terms of maintenance.

Another option would be

var items = new Array('foo', 'bar', 'baz');
for (i in items) {
    var item = items[i];

But that's also bad code as it defines a structure (Array) with lots of overhead where none is needed.

Sebastian
  • 2,472
  • 1
  • 18
  • 31

2 Answers2

6

Instead of using i in items use let i of items, this is because in gets attribute names, but of actually iterates through the array properly.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
2

A good option is to use the forEach like:

['foo', 'bar', 'baz'].forEach(function(item){ console.log(item); })

for loops only work well with object object

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Kubwimana Adrien
  • 2,463
  • 2
  • 8
  • 11