Reputation: 2733
Trying to generate an array of random numbers:
const arr = await generateValues(20, 500);
async function generateValues(numOfValues, max){
return await Promise.all(
new Array(numOfValues).map(() => Math.ceil(Math.random() * max))
);
}
const arr
is returning an array of length 20 but are all undefined
.
Upvotes: 1
Views: 373
Reputation: 3502
You might not aware of map
, it does not work with the blank or empty array. you have to use fill
to insert at least one element.
try it.
async function generateValues(numOfValues, max){
return await Promise.all(
new Array(numOfValues).fill(0).map(() => Math.ceil(Math.random() * max))
);
}
const arr = await generateValues(20, 500);
Upvotes: 1
Reputation: 4596
map
ignores empty elements in the array, so you have to use fill
first.
var arr = new Array( 20 ).fill( 0 ).map( () => { ... } )
Upvotes: 3