Home > other >  Is it possible to know when I am on the last element in a for loop?
Is it possible to know when I am on the last element in a for loop?

Time:11-12

I am looping through a list to extract data point, but would like to know when I am on the last element (a certain function that is run in the for loop should not be run when its the last element)

  for(final eachLine in _blocks){
    //
    _finalString = _finalString   eachLine   '\n';
  }

(I don't want to add \n) for the very last element, so I'd like to know when I'm on the very last element if its possible?

CodePudding user response:

There is no such way to do this with for-in/forEach style loop. Either use an iterator, a for loop with an index, or for this specific case you can use the String.join method:

var _finalString = _blocks.join('\n')

  • Related