We can access array elements using a for-of loop:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
How can I modify this code to access the current index too? I want to achieve this using for-of syntax, neither forEach nor for-in.
This question is related to
javascript
ecmascript-6
for-of-loop
es6 for...in
for(const index in [15, 64, 78]) {
console.log(index);
}
Array#entries
returns the index and the value, if you need both:
for (let [index, value] of array.entries()) {
}
In a for..of
loop we can achieve this via array.entries()
. array.entries
returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.
When the next()
method is called on the iterator key value pairs are generated. In these key value pairs the array index is the key and the array item is the value.
let arr = ['a', 'b', 'c'];_x000D_
let iterator = arr.entries();_x000D_
console.log(iterator.next().value); // [0, 'a']_x000D_
console.log(iterator.next().value); // [1, 'b']
_x000D_
A for..of
loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this with array.entries()
in the following manner:
array = ['a', 'b', 'c'];_x000D_
_x000D_
for (let indexValue of array.entries()) {_x000D_
console.log(indexValue);_x000D_
}_x000D_
_x000D_
_x000D_
// we can use array destructuring to conveniently_x000D_
// store the index and value in variables_x000D_
for (let [index, value] of array.entries()) {_x000D_
console.log(index, value);_x000D_
}
_x000D_
Also you can use JavaScript to solve your problem
iterate(item, index) {
console.log(`${item} has index ${index}`);
//Do what you want...
}
readJsonList() {
jsonList.forEach(this.iterate);
//it could be any array list.
}
_x000D_
You can also handle index yourself if You need the index, it will not work if You need the key.
let i = 0;
for (const item of iterableItems) {
// do something with index
console.log(i);
i++;
}
var fruits = ["apple","pear","peach"];
for (fruit of fruits) {
console.log(fruits.indexOf(fruit));
//it shows the index of every fruit from fruits
}
the for loop traverses the array, while the indexof property takes the value of the index that matches the array. P.D this method has some flaws with numbers, so use fruits
For those using objects that are not an Array
or even array-like, you can build your own iterable easily so you can still use for of
for things like localStorage
which really only have a length
:
function indexerator(length) {
var output = new Object();
var index = 0;
output[Symbol.iterator] = function() {
return {next:function() {
return (index < length) ? {value:index++} : {done:true};
}};
};
return output;
}
Then just feed it a number:
for (let index of indexerator(localStorage.length))
console.log(localStorage.key(index))
In this world of flashy new native functions, we sometimes forget the basics.
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
Clean, efficient, and you can still break
the loop. Bonus! You can also start from the end and go backwards with i--
!
Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i];
at the top of the loop for an easy, readable reference.
in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():
for(let [index, element] of document.querySelectorAll('div').entries()) {
element.innerHTML = '#' + index
}
Another approach could be using Array.prototype.forEach()
as
Array.from({_x000D_
length: 5_x000D_
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {_x000D_
console.log(val, index)_x000D_
})
_x000D_
Source: Stackoverflow.com