Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to unnamed array in Array.forEach

Is there any way to access the target object's length property when using the forEach loop over an unnamed array?

# I'd like to be able to do something like:
[1, 2, 3].forEach (n, i) -> console.log n is < (arr.length - 1)
like image 789
pdoherty926 Avatar asked Aug 24 '11 06:08

pdoherty926


Video Answer


1 Answers

The callback of Array.forEach takes tree arguments: value, index, and the array being traversed.

So you can do that:

[1, 2, 3].forEach (n, i, thearray) -> console.log n is < (thearray.length - 1)

Javascript:

[1, 2, 3].forEach(function(n, i, thearray) {
    console.log(n < thearray.length - 1);
});
like image 160
Arnaud Le Blanc Avatar answered Sep 26 '22 00:09

Arnaud Le Blanc