Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional loop given a number instead of an array [duplicate]

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

like image 493
Alexander Mills Avatar asked May 18 '16 03:05

Alexander Mills


People also ask

Can we loop on number in JavaScript?

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.

How do you take the value out of a for loop?

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.

What can I use instead of a for 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.

How do you declare an array with repeated values?

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.


2 Answers

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

like image 70
Rajshekar Reddy Avatar answered Oct 04 '22 00:10

Rajshekar Reddy


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.

like image 39
RobG Avatar answered Oct 03 '22 22:10

RobG