[英]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在此处输入图像描述我想要的是创建一个带有随机数的数组,然后我可以使用 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我不明白为什么 foreach 不起作用,因为 console.log(randomNumber) 工作得很好
When the forEach
call happens, randomNumber
doesn't have any entries in it, so forEach
doesn't do anything.当forEach
调用发生时, randomNumber
中没有任何条目,因此forEach
不执行任何操作。 You're only adding entries later , when the setInterval
callback runs.您只是稍后添加条目,当setInterval
回调运行时。 That happens long after (in computer terms) your forEach
call.这发生在(用计算机术语)您的forEach
调用之后很久。
I think for your purpose you should do something like this.我认为为了你的目的,你应该做这样的事情。
Call getRandomArray()
after clearInterval(myInterval)
to get RandomArray
.在clearInterval(myInterval)
getRandomArray()
之后调用getRandomArray()
以获取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) }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.