[英]Create an array of arrays, in which every array has 10 random numbers
Here I try to understand how to create array of arrays: I created one array but how to create an array of arrays, in which every array has 10 random numbers?在这里,我尝试了解如何创建 arrays 数组:我创建了一个数组,但是如何创建一个 arrays 数组,其中每个数组都有 10 个随机数?
var arrRand = [];
while(arrRand.length < 10){
var random = Math.floor(Math.random() * 10) + 1;
if(arrRand.indexOf(random) === -1) arrRand.push(random);
}
console.log(arrRand);
A functional approach with every number being random.每个数字都是随机的功能方法。
let x = Array(4).fill().map( () => Array(10).fill().map( () => Math.floor(Math.random() * 10) ) ); console.log(x);
You can use Math.random
and a nested for loop
.您可以使用Math.random
和嵌套for loop
。 Here is an example:这是一个例子:
let arr = []; for(let i = 0; i < 4; i++){ let current = []; for(let j = 0; j < 10; j++) current.push(Math.floor(Math.random() * 10)); arr.push(current); } console.log(arr)
In order to keep clean and dry code, you can use map function in ES6 syntax.为了保持干净和干燥的代码,您可以在 ES6 语法中使用map function。
const x = [...Array(6)].map( () => [...Array(10)].map( () => Math.floor(Math.random() * 10) + 1 ) ) console.log(x)
let a = Array(4).fill(Array(10).fill(null))
Then fill it with Math.random()
in loop然后在循环中用Math.random()
填充它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.