simon blanco
simon blanco

Reputation: 148

how can I create an array with random numbers?

enter image description herewhat I want is to create an array with random numbers so I can then add them to another array with a foreach

let jsonlength = this.accesoriosJson.length
let a = 0;
let randomNumber = new Array()
var myInterval = setInterval(function(){
  a++
  if (a > jsonlength) {
    clearInterval(myInterval);
  }else{
     randomNumber.push(Math.ceil(Math.random()*10))
  }
},100)

console.log(randomNumber) 

randomNumber.forEach(valor => {console.log(valor)}) 

I don't understand why the foreach doesn't work because console.log(randomNumber) works just fine

Upvotes: 0

Views: 53

Answers (2)

Vivek Jain
Vivek Jain

Reputation: 2864

I think for your purpose you should do something like this.

Call getRandomArray() after clearInterval(myInterval) to get RandomArray.

let jsonlength = 6;
let a = 0;
let randomNumber = new Array()
var myInterval = setInterval(function() {
  a++
  if (a > jsonlength) {
    clearInterval(myInterval);
    getRandomArray();
  } else {
    randomNumber.push(Math.ceil(Math.random() * 10))
  }
}, 0);

function getRandomArray() {
  console.log(randomNumber);

  randomNumber.forEach(valor => {
    console.log(valor)
  })
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074148

When the forEach call happens, randomNumber doesn't have any entries in it, so forEach doesn't do anything. You're only adding entries later, when the setInterval callback runs. That happens long after (in computer terms) your forEach call.

Upvotes: 4

Related Questions