Kousha
Kousha

Reputation: 36209

UnderscoreJS - For loop the length of an array

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!

Upvotes: 0

Views: 337

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

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 ...
}

Upvotes: 0

univerio
univerio

Reputation: 20518

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

_.times(myArray.length, function(i) {...})

Upvotes: 2

Related Questions