简体   繁体   中英

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?

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

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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