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.
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.
Use Array.prototype.keys
:
for (const index of ["a", "b", "c", "d", "e"].keys()) {
console.log(index);
}
If you want to access both the key and the value, you can use Array.prototype.entries()
with destructuring:
for (const [index, value] of ["a", "b", "c", "d", "e"].entries()) {
console.log(index, value);
}
yield
keyword. But I need access to the index for my use case, so... basic old ;;
loop it is, I guess. –
Devoir .entires()
? –
Inerney .entries()
to have access to the index. –
Devoir Array.from(myHtmlCollection)
, in older notations Array.prototype.slice.call( htmlCollection )
. Then you can call .entries()
on the array. –
Preraphaelite Array#entries
returns the index and the value, if you need both:
for (let [index, value] of array.entries()) {
}
document.styleSheets[0].cssRules.entries()
or even document.styleSheets.entries()
and probably many other DOM iterable structures. Still have to use _.forEach()
from lodash
–
Grainfield for (var value of document.styleSheets) {}
. If you do need the index you can convert the value to an array first via Array.from
: for (let [index, value] of Array.from(document.styleSheets)) {}
. –
Cowgirl Array.from
is FTW –
Grainfield 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.
break
a for-of
and for (let [index, value] of array.entries())
is far easier to read. Going backwards is as easy as adding .reverse()
. –
Mouseear for
loop is ~8 times faster than the for of array.entries()
. jsbench.me/6dkh13vqrr/1 –
Abbyabbye ;;
is work with async await code –
Giga 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'];
let iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
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'];
for (let indexValue of array.entries()) {
console.log(indexValue);
}
// we can use array destructuring to conveniently
// store the index and value in variables
for (let [index, value] of array.entries()) {
console.log(index, value);
}
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++;
}
Another approach could be using Array.prototype.forEach()
as
Array.from({
length: 5
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {
console.log(val, index)
})
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
}
entries
method for them. –
Tandie Just create a variable before the loop and assign an integer value.
let index = 0;
and then use addition assignment operator into the loop scope
index += 1;
That's It, check the below snippet example.
let index = 0;
for (const j of [1, 2, 3, 4, 5]) {
console.log('index ',index);
index += 1;
}
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))
You can try making use of indexOf menthod inside for of... loop
let arrData = [15, 64, 78]
for (const data of arrData) {
console.log("data value", data, "index of data ", arrData.indexOf(data));
}
O(n^2)
complexity :( –
Agone 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.
}
es6 for...in
for(const index in [15, 64, 78]) {
console.log(index);
}
for...of
loop not a for...in
–
Leaper for...in
is part of the original ECMAScript specification (i.e."es1") . Also, note that for...in
is meant for iterating over object properties. While it can iterate over arrays, it may not do so in the expected order. See more in the MDN documentation –
Biomedicine for...of
loop and not just general itteration... –
Wenoa © 2022 - 2024 — McMap. All rights reserved.
for-of
with.entries()
and it's twice as slow compared to.forEach()
. jsperf.com/for-of-vs-foreach-with-index – Whipperin