Access to Es6 Array Element Index Inside For-Of Loop

Access to ES6 array element index inside for-of loop

Use Array.prototype.keys:

for (const index of [1, 2, 3, 4, 5].keys()) {  console.log(index);}

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

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.

What is the simple way to get value and index on For of loop out of an array in Javascript / ReactNative?

use this

for (const [index, value] of array.entries()) {
console.log(index, value);
}

How can the current number of i be accessed in a for of loop?

nothing simple ... if you want "simple access" to both the item and the index in a loop over an array, use forEach e.g.

array.forEach(function(item, index) { 
...
});

or as T.J. Crowder pointer out (and I missed the ES6 tag)

array.forEach((item, index) => { 
...
});

like many programming languages, javascript has multiple ways to do similar things, the skill is in choosing the right tool for the job

How to loop through an array containing objects and access their properties

Use forEach its a built-in array function. Array.forEach():

yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});


Related Topics



Leave a reply



Submit