Operators like are .each() automatically aware if all items in a list have been processed. But there are two other reasons it is useful to now if the first or last item is being handled:
- adding a prefix (for first item) or suffix (to last item) to the output of the loop.
- detecting if a join is needed, between list items, in the output.
Detecting first or last position
This is most easily done using List/Set.first or List/Set.last. Note that .first and .last are not operators, but simply return the value of that item in the source list.
In a case where the loop is being used to create a string, a prefix can be added to the overall output by testing .first. The code setting the prefix needs to be the very first code inside the loop so the suffix is added to the output before the first item's data:
$MyList.each(anItem){
if(anItem==$MyList.first){
// code for prefix here
};
// other in-loop per item code
};
For a suffix, do the same but test .last and put the suffix code at the end of the in-loop code so the suffix comes after the output of the last loop item's data:
$MyList.each(anItem){
// other in-loop per item code
if(anItem==$MyList.last){
// code for suffix here
};
};
Adding join data between list items is explored in adding joins in loops.