这里我试图理解如何创建数组数组:我创建了一个数组,但如何创建一个数组数组,其中每个数组都有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);
每个数字都是随机的函数方法。
let x = Array(4).fill().map(
() => Array(10).fill().map(
() => Math.floor(Math.random() * 10)
)
);
console.log(x);
您可以使用Math.random
和嵌套的for loop
。以下是一个示例:
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)
为了保持代码的干净和干燥,您可以在ES6语法中使用map函数。
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))
然后在环路中填充Math.random()