How can I get the next item in an array when iterating?
for (let item of list) {
// item @ index + 1
}
I know I could use the loop with this syntax but prefer the previous one.
for (i = 0; i < list.length; i++) {}
The loop does not offer any syntax to do this, but you can combine the destructuring syntax introduced in ES6 with calling the entries() method on the array:
for (const [i, v] of ['a', 'b', 'c'].entries()) {
console.log(i, v)
}
Here is the best example you can refer
let list = [4, 5, 6];
for (let i in list) {
console.log(i); // "0", "1", "2",
}
for (let i of list) {
console.log(i); // "4", "5", "6"
}
Use in
to get the index:
for (let index in list) {
// Use index
}
Or use forEach
:
list.forEach((item, index) => {...});
A simple solution would be to iterate the keys of the list via for(..in..)
and, per-iteration, add one to the current index to obtain the index of the next
value from the current iteration like so:
let list = [4, 5, 6];
for (let i in list) {
const next = list[Number.parseInt(i) + 1];
console.log('curr=', list[i]);
console.log('next=', next);
console.log('---');
}
Some points to consider with this are:
next
value will be undefinedi
needs to be parsed to an interger to ensure that the "add one" step returns the index of the next value (rather than a string concatenation)