如何创建一个包含 40 个元素的数组,随机值从 0 到 39 ?喜欢
[4, 23, 7, 39, 19, 0, 9, 14, ...]
我尝试使用这里的解决方案:
http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm
但我得到的数组很少是随机的。它生成了很多连续数字块......
如何创建一个包含 40 个元素的数组,随机值从 0 到 39 ?喜欢
[4, 23, 7, 39, 19, 0, 9, 14, ...]
我尝试使用这里的解决方案:
http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm
但我得到的数组很少是随机的。它生成了很多连续数字块......
最短方法(ES6)
// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));
享受!
这是一个对唯一数字列表进行洗牌的解决方案(永远不会重复)。
for (var a=[],i=0;i<40;++i) a[i]=i;
// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a);
如果您想允许重复值(这不是 OP 想要的),请查看其他地方。:)
ES5:
function randomArray(length, max) {
return Array.apply(null, Array(length)).map(function() {
return Math.round(Math.random() * max);
});
}
ES6:
randomArray = (length, max) => [...new Array(length)]
.map(() => Math.round(Math.random() * max));
更短的 ES6 方法:
Array(40).fill().map(() => Math.round(Math.random() * 40))
此外,你可以有一个带参数的函数:
const randomArray = (length, max) =>
Array(length).fill().map(() => Math.round(Math.random() * max))
最短的:-)
[...Array(40)].map(e=>~~(Math.random()*40))