我该如何创建一个由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特性,现在可以通过以下方式实现:
function getRandomInt(min, max) {
"use strict";
if (max < min) {
// Swap min and max
[min, max] = [min, max];
}
// Generate random number n, where min <= n <= max
let range = max - min + 1;
return Math.floor(Math.random() * range) + min;
}
let values = Array.from({length: 40}, () => getRandomInt(0, 40));
console.log(values);
由于数字范围受限,我建议最好的方法是生成数组,用0到39(顺序)填充它,然后对其进行洗牌。
var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
myArray.push(Math.floor(Math.random()*limit));
}
每天都可以使用奇怪的单行解决方案。
数组中的值是完全随机的,因此当您使用这些代码片段时,它们将不同。
一个包含小写随机字符的数组(长度为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' ]
一个长度为10的数组,包含0到99之间的随机整数
Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })
[ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]
一个包含随机日期的数组(从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 ]
一个长度为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' ]
这里还有其他有用的东西 https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js
使用 Es6
new Array(40).fill(0).map(_ => Math.random() * 40 | 0)
Math.random()
生成浮点数,需要转换为整数,可以使用按位或(|)运算符。[...Array(40)].map(_ => Math.random() * 40 | 0)
使用[...Array(40)]
代替new Array(40).fill(0)
——它将克隆长度为40的空(undefined)数组。
使用Array.from
arrayLike
要转换为数组的类似数组或可迭代对象。
mapFn
(可选)在数组的每个元素上调用的映射函数。
Array.from({length: 10}, () => Math.floor(Math.random() * 100));
我们将使用Set
来实现,因为我们知道集合只允许添加唯一的值。
let set = new Set();
while (set.size <= 40) {
set.add((Math.random() * 400) | 0);
}
let randomArray = [...set];
但是有一点很重要,那就是您需要乘以比数组长度更大的数字……否则生成唯一数字的时间太长,可能会导致执行冻结很长时间。尝试取比我这里取的400大10倍的数字。
function shuffle(maxElements) {
//create ordered array : 0,1,2,3..maxElements
for (var temArr = [], i = 0; i < maxElements; i++) {
temArr[i] = i;
}
for (var finalArr = [maxElements], i = 0; i < maxElements; i++) {
//remove rundom element form the temArr and push it into finalArrr
finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0];
}
return finalArr
}
let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */
var random_array = new Array(40).fill().map((a, i) => a = i).sort(() => Math.random() - 0.5);
keys
函数: Array.from(Array(40).keys()).sort(_ => Math.random() - .5)
? 你甚至可以疯狂地使用展开运算符!但现在对我来说太激动人心了。 - Yeticonst randomRange = length => {
const results = []
const possibleValues = Array.from({ length }, (value, i) => i)
for (let i = 0; i < length; i += 1) {
const possibleValuesRange = length - (length - possibleValues.length)
const randomNumber = Math.floor(Math.random() * possibleValuesRange)
const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange
const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)
results.push(nextNumber)
}
return results
}
randomRange(5) // [3, 0, 1, 4, 2]
从@Phrogz建议的页面
for (var i=0,nums=[];i<49;i++) nums[i]={ n:i, rand:Math.random() };
nums.sort( function(a,b){ a=a.rand; b=b.rand; return a<b?-1:a>b?1:0 } );
Math.random()
40 次会产生略微不同的结果,因为它将强制每个数字只出现一次且不重复。 - Mu Mind