Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying the next item in current for of loop iteration Typescript

In my TypeScript project, I want to compare the values in an Array with the next value. If I am doing this in JavaScript I would do something like this:

//JS
for (var i = 0; i < codeBlocks.length; i++) {
    var j = i + 1;
    if (codeBlocks[i] > codeBlocks[j]) {return true;}
    return false;
}

However, I really like the Typescript for of syntax as it is much more readable.

//TS
for (let codeBlock of codeBlocks) {
    //logic
}

Is there a way of describing the "next iteration" value in the typescript for...of loop?

like image 974
George Edwards Avatar asked Oct 18 '25 00:10

George Edwards


1 Answers

You can use entries()

for (var [index, codeBlock] of codeBlocks.entries()) 
{ 
  // your code you can use index 
}

DEMO

Example snippet:

var test = ['a','b','c']
for (var [index, cur] of test.entries()) 
{ 
  var j = index + 1;
  console.log("Current value: "+cur+"  Next value: "+test[j])
}
like image 136
Manwal Avatar answered Oct 19 '25 14:10

Manwal