简体   繁体   中英

how can I create an array with random numbers?

enter image description here what 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

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.

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) }) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM