# How to call a function a random number of times to fill an array

Page 1 of 1

## 2 Replies - 812 Views - Last Post: 05 November 2014 - 11:51 AM

### #1 stinkytotoro

Reputation: 0
• Posts: 53
• Joined: 31-May 14

# How to call a function a random number of times to fill an array

Posted 04 November 2014 - 05:17 PM

I need to call the addRandom function to the populate function a random number of times between 2-50 to generate an array of 2-50 values.(inclusively)

```
function getUserInput() {
'use strict';
var min = parseInt(document.getElementById("min").value);
var max = parseInt(document.getElementById("max").value);

if (validateNum(min,0,500) === false) {
}
else{
document.getElementById("output").innerHTML=randomNum;
}
}

function validateNum(value, min,max){
'use strict';
if (value >= min && value <= max)
{
return true;
}
else {
return false;
}
}

function addRandom(min,max){//generate a random number from the passed in min to max values
'use strict';
var array=[];
var random= Math.floor(Math.random()*(max-min+1)+ min);
array.push(random);
return array;
}

function populate(){

}

```

This post has been edited by stinkytotoro: 04 November 2014 - 05:19 PM

Is This A Good Question/Topic? 0

## Replies To: How to call a function a random number of times to fill an array

### #2 stinkytotoro

Reputation: 0
• Posts: 53
• Joined: 31-May 14

## Re: How to call a function a random number of times to fill an array

Posted 04 November 2014 - 06:08 PM

```function populate(min,max){
var ran=Math.floor((Math.random() * 40-2) + 2);
var array=[];
for(var i= 0; i<ran;i++){
}
return array;

}

```

/> this seems to be working I don't know if its the greatest though

This post has been edited by stinkytotoro: 04 November 2014 - 06:11 PM

### #3 Blindman67

Reputation: 140
• Posts: 620
• Joined: 15-March 14

## Re: How to call a function a random number of times to fill an array

Posted 05 November 2014 - 11:51 AM

You need to use a loop to add the numbers.
I assume you want to add 2-50 random values between 2-50 (or what ever valid input the user enters) to the array.

```var array = []; // empty array
var i;         // loop counter
for(i = min; i <= max; i++){ //loop for each required random.
array.push(Math.floor(Math.random()*(max-min+1)+ min));
}

array += Math.random(); // will not work;
```

To display the array.

```var i;          //loop counter
var html = "";  // string you are creating for display
for(i = 0; i < array.length; i++){  // loop the length of the array
html += array[i]+"<br>";        // add each array item to the display string
}
element.innerHTML = html;   // display the items.
```

One extra tip. You may wish to place "use strict"; at the very top of the script rather than at the top of each fuction. Saves you from having to repeatedly add it to your code.