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
Loop Number of Times Using Functionsconst loop = (times, callback) => { for (let i = 0; i < times; i++) { callback(i); } }; Note that the iteration in this case will start at 0. Note that we have access to the i variable inside the callback function, since we passed it down to the callback inside the loop function.
set the value of it inside the loop with your value desired. call the change event along for the input element. Add a event listener for the change of input and get that value which is obviously outside the loop.
> forEach() This method takes a function and executes it for every element. This alternative for “for” loop is only used when we do not have a better higher order function to use in that situation.
var repeatelem = function(elem, n){ // returns an array with element elem repeated n times. var arr = []; for (var i = 0; i <= n; i++) { arr = arr. concat(elem); }; return arr; }; javascript.
If you have a number and you want to create a loop then you can use the number in limiter condition in the for loop.
for(var i = 0; i < number; i++)
Edit 1: you can use foreach
on arrays only, in that case since you have a number already you can create a array of that length and then use the foreach on it.
var foo = new Array(number).fill(0);
foo.foreach()
Also another option is
var N = 18;
Array.apply(null, {length: N}).map(Number.call, Number)
result [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
Many more options available in this thread Create a JavaScript array containing 1...N
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With