0

Say I have an array myArray of some length N. I want to loop Nth time. In pure Javascript, that would be:

for (var i = 0; i < myArray.length; i++) {}

Is there a way to also do this in UnderscoreJS? I know I can use _.each in the following way:

_.each(myArray, function(a) {
});

but I don't particularly want to loop through the entries. There is no reason why i want to do this. This is purely a thought experiment and I was just wondering if there is a way of doing this!

8
  • What's wrong with _.each? Doesn't it call the function N times? Commented Aug 16, 2014 at 20:31
  • There is nothing wrong with _.each. It does run N times. But I was just wondering if I could create the exact same thing as the for loop in Javascript (i.e. just loop with the index, not the actual item). Commented Aug 16, 2014 at 20:32
  • 3
    _.times(myArray.length, function() {...})? Commented Aug 16, 2014 at 20:40
  • @univerio: That's pretty close to an answer. A documentation reference, some explanation, and maybe an example is all it needs. Commented Aug 16, 2014 at 20:41
  • @univerio, this works perfectly. If you post it, I can vote it. Commented Aug 16, 2014 at 20:42

2 Answers 2

2

You can use the _.times() function to execute a callback n times:

_.times(myArray.length, function(i) {...})
Sign up to request clarification or add additional context in comments.

Comments

0

Note that you can use each and just use the index and ignore the actual entries:

_.each(myArray, function(a, i) {
   ... do something with i but not a ...
}

2 Comments

Thanks but as I said, I know I can do that. I was looking to see if there is a way only get the index. Please see the accepted the answer to what I was looking for.
It wasn't clear that you knew about the iterator function getting the index as a second argument, since you didn't have such an argument in your example code. That's the part I was trying to get across in case you weren't aware of it and thought you would have to keep your own counter or something, which might influence your desire not to go that route.

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.