Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get loop counter/index using for…of syntax in JavaScript

Caution:

question still applies to for…of loops.> Don't use for…in to iterate over an Array, use it to iterate over the properties of an object. That said, this


I understand that the basic for…in syntax in JavaScript looks like this:

for (var obj in myArray) {
    // ...
}

But how do I get the loop counter/index?

I know I could probably do something like:

var i = 0;
for (var obj in myArray) {
    alert(i)
    i++
}

Or even the good old:

for (var i = 0; i < myArray.length; i++) {
    var obj = myArray[i]
    alert(i)
}

But I would rather use the simpler for-in loop. I think they look better and make more sense.

Is there a simpler or more elegant way?


In Python it's easy:

for i, obj in enumerate(myArray):
    print i
like image 595
hobbes3 Avatar asked Apr 16 '12 18:04

hobbes3


People also ask

Can you get index in for of loop?

You can access the index even without using enumerate() . Using a for loop, iterate through the length of my_list . Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index] .

What is the for loop syntax in JavaScript?

for/in - loops through the properties of an object. for/of - loops through the values of an iterable object. while - loops through a block of code while a specified condition is true. do/while - also loops through a block of code while a specified condition is true.

Can we get index in forEach JavaScript?

Get the Current Array Index in JavaScript's forEach() In simple terms, you can look at the Array object as an array in any other programming language. It is essentially a class that encapsulates an array (an ordered list of values) and all necessary methods you might need to perform array operations.

How do you use a for loop?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.


2 Answers

for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

Or ES6’s Array.prototype.entries, which now has support across current browser versions:

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}

For iterables in general (where you would use a for…of loop rather than a for…in), there’s nothing built-in, however:

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}

demo

If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.

like image 87
Ry- Avatar answered Oct 16 '22 16:10

Ry-


In ES6, it is good to use a for... of loop. You can get index in for... of like this

for (let [index, val] of array.entries()) {
  // your code goes here    
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

like image 366
rushUp Avatar answered Oct 16 '22 14:10

rushUp