Javascript 创建具有随机值的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5836833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an array with random values
提问by Alexandra
How can I create an array with 40 elements, with random values from 0 to 39 ? Like
如何创建一个包含 40 个元素的数组,随机值从 0 到 39 ?喜欢
[4, 23, 7, 39, 19, 0, 9, 14, ...]
I tried using solutions from here:
我尝试使用这里的解决方案:
http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm
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...
但我得到的数组很少是随机的。它生成了很多连续数字块......
采纳答案by Phrogz
Here's a solution that shuffles a list of uniquenumbers (no repeats, ever).
这是一个对唯一数字列表进行洗牌的解决方案(永远不会重复)。
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);
If you want to allow repeated values (which is not what the OP wanted) then look elsewhere. :)
如果您想允许重复的值(这不是 OP 想要的),请查看其他地方。:)
回答by simonbor
The shortest approach (ES6)
最短方法(ES6)
// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));
Enjoy!
享受!
回答by Eugene Kulabuhov
ES5:
ES5:
function randomArray(length, max) {
return Array.apply(null, Array(length)).map(function() {
return Math.round(Math.random() * max);
});
}
ES6:
ES6:
randomArray = (length, max) => [...new Array(length)]
.map(() => Math.round(Math.random() * max));
回答by Damjan Pavlica
Even shorter ES6 approach:
更短的 ES6 方法:
Array(40).fill().map(() => Math.round(Math.random() * 40))
Also, you could have a function with arguments:
此外,你可以有一个带参数的函数:
const randomArray = (length, max) =>
Array(length).fill().map(() => Math.round(Math.random() * max))
回答by Curt
Shortest :-)
最短:-)
[...Array(40)].map(e=>~~(Math.random()*40))
[...Array(40)].map(e=>~~(Math.random()*40))
回答by Robert
Math.random()
will return a number between 0 and 1(exclusive). So, if you want 0-40, you can multiple it by 40, the highest the result can ever be is what you're multiplying by.
Math.random()
将返回 0 到 1(不包括)之间的数字。所以,如果你想要 0-40,你可以将它乘以 40,结果可能是你乘以的最高值。
var arr = [];
for (var i=0, t=40; i<t; i++) {
arr.push(Math.round(Math.random() * t))
}
document.write(arr);
回答by Jared Beck
.. the array I get is very little randomized. It generates a lot of blocks of successive numbers...
.. 我得到的数组很少是随机的。它生成了很多连续数字块......
Sequences of random items often contain blocks of successive numbers, see the Gambler's Fallacy. For example:
随机项目的序列通常包含连续数字块,请参阅赌徒谬误。例如:
.. we have just tossed four heads in a row .. Since the probability of a run of five successive heads is only 1?32 .. a person subject to the gambler's fallacy might believe that this next flip was less likely to be heads than to be tails. http://en.wikipedia.org/wiki/Gamblers_fallacy
.. 我们刚刚连续掷了四个正面.. 因为连续五个正面的概率只有 1?32 .. 一个受赌徒谬论影响的人可能认为下一次翻转的可能性小于正面成为尾巴。 http://en.wikipedia.org/wiki/Gamblers_fallacy
回答by Pointy
Since the range of numbers is constrained, I'd say the best thing to do is generate the array, fill it with numbers zero through 39 (in order), then shuffle it.
由于数字范围受到限制,我认为最好的做法是生成数组,用数字 0 到 39(按顺序)填充它,然后对其进行洗牌。
回答by Rafael
let randomNumber = Array.from({length: 6}, () => Math.floor(Math.random() * 39));
limited the array to 6 values to make it easy to see.
将数组限制为 6 个值,以便于查看。
回答by PADYMKO
Quirk single-line solutions on every day.
每天都有 Quirk 单线解决方案。
Values in arrays is total random, so when you will be use this snippets, it will different.
数组中的值是完全随机的,所以当你使用这个片段时,它会有所不同。
An array (length 10) with random chars in lowercase
带有小写随机字符的数组(长度为 10)
Array.apply(null, Array(10)).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); })
[ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j' ]
[ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j' ]
An array (length 10) with random integer numbers from 0 to 99
具有从 0 到 99 的随机整数的数组(长度为 10)
Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })
[ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]
[ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]
An array random dates (from 10 years to ago to now)
数组随机日期(从 10 年前到现在)
Array.apply(null, Array(10)).map(function() { return new Date((new Date()).getFullYear() - Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 29) )})
[ 2008-08-22T21:00:00.000Z, 2007-07-17T21:00:00.000Z,
2015-05-05T21:00:00.000Z, 2011-06-14T21:00:00.000Z,
2009-07-23T21:00:00.000Z, 2009-11-13T22:00:00.000Z,
2010-05-09T21:00:00.000Z, 2008-01-05T22:00:00.000Z,
2016-05-06T21:00:00.000Z, 2014-08-06T21:00:00.000Z ]
[2008-08-22T21:00:00.000Z,2007-07-17T21:00:00.000Z,
2015-05-05T21:00:00.000Z,2011-06-14T21:00:00.000Z,
2009-07-23T21 :00:00.000Z, 2009-11-13T22:00:00.000Z,
2010-05-09T21:00:00.000Z, 2008-01-05T22:00:00.000Z,
5006-00Z, 5006-00Z 2014-08-06T21:00:00.000Z]
An array (length 10) random strings
一个数组(长度为 10)随机字符串
Array.apply(null, Array(10)).map(function() { return Array.apply(null, Array(Math.floor(Math.random() * 10 + 3))).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); }).join('') });
[ 'cubjjhaph', 'bmwy', 'alhobd', 'ceud', 'tnyullyn', 'vpkdflarhnf', 'hvg', 'arazuln', 'jzz', 'cyx' ]
['cubjjhaph'、'bmwy'、'alhobd'、'ceud'、'tnyullyn'、'vpkdflarhnf'、'hvg'、'arazuln'、'jzz'、'cyx']
Other useful things you may found here https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js
您可以在这里找到其他有用的东西https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js