繁体   English   中英

创建一个 arrays 数组,其中每个数组有 10 个随机数

[英]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);

每个数字都是随机的功能方法。

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

然后在循环中用Math.random()填充它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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