Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  17] [ 1]  / answers: 1 / hits: 40598  / 8 Years ago, wed, may 18, 2016, 12:00:00

Say I have a number 18, instead of an array, in hand.



What is the best way to create a functional loop in JS given a number X instead of array of X elements?



I can do this:



[1,2,3].forEach(function(){

));


but if I have the number 3



I can do



for(var i = 0; i < 3; i++){

}


but I want that loop to be functional instead


More From » node.js

 Answers
29

I don't understand why you want to do this. An equivalent to:


[1,2,3].forEach(function(){ ... ));

Is


var limit = n;
while (--limit) {( // Note: 0 is falsy
function(){ ... }
)(limit);}

Or if you really want to use an array structure, the following will do:


new Array(limit).fill(0).forEach(function(){...});

You might be interested in Myth of the Day: Functional Programmers Don't Use Loops.


[#62124] Monday, May 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lidialyrick

Total Points: 737
Total Questions: 104
Total Answers: 89

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
lidialyrick questions
;