arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});
How to catch when the loop ending? I can do if(i == 3)
but I might don\'t kn
The 2018 ES6+ ANSWER IS:
const arr = [1, 2, 3];
arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
const arr= [1, 2, 3]
arr.forEach(function(element){
if(arr[arr.length-1] === element){
console.log("Last Element")
}
})
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.