Create an array with random values Ask Question

Create an array with random values Ask Question

How can I create an array with 40 elements, with random values from 0 to 39 ? Like

[4, 23, 7, 39, 19, 0, 9, 14, ...]

I tried using solutions from here:

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

but the array I get is very little randomized. It generates a lot of blocks of successive numbers...

ベストアンサー1

The shortest approach (ES6):

// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));

おすすめ記事