【发布时间】:2017-09-22 18:36:31
【问题描述】:
我正在尝试编写一个在给定范围内产生四个不相等随机数的函数,但该函数当前在while (selection[i] in selection.slice().splice(i) 行失败。这一行应该检查当前 (i'th) 值是否被任何其他随机值共享,但目前它似乎什么也没做——也许我错误地使用了in?任何帮助将不胜感激。
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]);
}
}
【问题讨论】:
标签: javascript canvas random slice splice