我正在尝试编写一个函数,它可以在给定范围内生成四个不相等的随机数,但该函数目前在while (selection[i] in selection.slice().splice(i)
行失败。此行应检查当前(i
'th)值是否由任何其他随机值共享,但目前看起来什么都不做 - 可能我错误地使用了in
?任何帮助,将不胜感激。Javascript - 多个不等随机数生成器
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
所以:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
selected=[];
function randomSelection() {
var notselected=[];
for (var i=0; i<25; i++) {
if(!contains(selected, i)) {
notselected.push(i);
}
}
var selection=[notselected[Math.floor(Math.random() * notselected.length)],
notselected[Math.floor(Math.random() * notselected.length)],
notselected[Math.floor(Math.random() * notselected.length)],
notselected[Math.floor(Math.random() * notselected.length)]];
for (var i=0; i<selection.length; i++) {
while (selection[i] in selection.slice().splice(i)) {
alert('Hello!')
selection[i] = notselected[Math.floor(Math.random() * notselected.length)];
}
}
for (var i=0; i<selection.length; i++) {
selected.pop(selection[i]);
}
}