简体   繁体   English

如何创建一个带有随机数的数组?

[英]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.

相关问题 如何用不同的随机数填充矩阵数组 - How can I populate matrix array with different random numbers 如何在 javascript 中生成一个波动为 1 的随机数数组? - How can I generate an array of random numbers that fluctuate by 1 in javascript? 如何找到不在数组中的随机数? 想要遍历随机数直到找到一个 - How can I find a random number not located in an array? Want to loop through random numbers until one is found 如何创建用户提供的数字数组并将其映射到数字立方体的数组? - How can I create an array of user-provided numbers and map that to an array of the numbers' cubes? 如何创建一个包含非重复数据而不是随机数的数组? - How to create an Array which contains unduplicated and not random numbers? 下面的代码如何创建一个包含所有随机数的数组? - How does the below code create an array with a all random numbers? 如何生成数组元素的随机组合,使它们的值之和介于两个数字之间? - How can I generate a random combination of array elements so that the sum of their values is between two numbers? 如何使用JavaScript创建随机数列表? - How do I create a list of random numbers using JavaScript? JS创建具有唯一随机数的数组 - JS create an array with unique random numbers 如何生成随机数,然后排除数字数组 - How to generate Random numbers, then exclude array of numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM