Marcel Marcel - 3 months ago 6
Javascript Question

How to create n different arrays with 6 random numbers each. - Javascript/Jquery

I want to create 1 - 12 arrays of 6 random numbers each.
At the moment I can only create one. So I don't know how to loop this.

This is my code so far:

<script type="text/javascript">
function schleife() {

var arr = [];
var krams = [];

for(i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}

arr.push(krams.toString() + "<br /><br />");
$(".bsp2").append(arr);

}

function uebertrag() {
schleife();
}
</script>

Answer

You need to create new function: e.g. getArrayOfRandomNumbers

function getArrayOfRandomNumbers() {
  var krams = []

  for(var i=1; i<=6; i++) { 
    var zufall = Math.floor((Math.random() * 49) + 1)          
    krams.push(zufall++)
  }

  return krams
}

And now you can invoke this function in loop:

for (var j = 0; j < 12; j++) {
  var arrayOfRandomNumber = getArrayOfRandomNumbers()
  //do something with this array, e.g. append

  $(".bsp2").append(arrayOfRandomNumber.toString())
}
Comments