5

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)
2
  • Well, it's a constant array, so you know the length. In this example, it's 3. What do you need it for? Commented Aug 24, 2011 at 7:15
  • 3
    @daniel kullmann, the question also applies for code like getSomething().forEach ... Commented Aug 24, 2011 at 11:35

1 Answer 1

6

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Note to self, RTFM!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.