我需要获取随机数,但不能多次使用同一数字。 我编写了以下函数来创建一个随机数,并检查它是否尚未使用。
function randomRecep(){
return Math.floor((Math.random() * 3));
}
function assignTemp(tempArr){
console.log("Started assign function, tempArr has: "+tempArr);
var num = randomRecep();
for (var i = 0; i < tempArr.length; i++) {
console.log("num is: " + num + ". check for doubles. tampArr["+i+"] is: "+tempArr[i]);
if (num == tempArr[i]){
console.log("FOUND DOUBLE! random num = "+num+" IS ALREADY IN array:"+tempArr)
assignTemp(tempArr);
break;
}
}
tempArr.push(num);
console.log("pushed " + num + "into array. now is:" + tempArr);
return num;
}
以下是控制台输出。似乎检查工作正常,但由于某种原因,在检查结束时,它不仅推送唯一的随机数并返回其值,而且程序还推送了所有先前的重复数并返回第一个随机数,而不是最后一张通过了支票的。为什么呢?
Started assign function, tempArr has: -1,2,1
code.js:104 num is: 1. check for doubles. tampArr[0] is: -1
code.js:104 num is: 1. check for doubles. tampArr[1] is: 2
code.js:104 num is: 1. check for doubles. tampArr[2] is: 1
code.js:106 FOUND DOUBLE! random num = 1 IS ALREADY IN array:-1,2,1
code.js:101 Started assign function, tempArr has: -1,2,1
code.js:104 num is: 1. check for doubles. tampArr[0] is: -1
code.js:104 num is: 1. check for doubles. tampArr[1] is: 2
code.js:104 num is: 1. check for doubles. tampArr[2] is: 1
code.js:106 FOUND DOUBLE! random num = 1 IS ALREADY IN array:-1,2,1
code.js:101 Started assign function, tempArr has: -1,2,1
code.js:104 num is: 0. check for doubles. tampArr[0] is: -1
code.js:104 num is: 0. check for doubles. tampArr[1] is: 2
code.js:104 num is: 0. check for doubles. tampArr[2] is: 1
code.js:113 pushed 0into array. now is:-1,2,1,0
这个结果很好,并且想法是到此为止。但过程继续进行:
code.js:113 pushed 1into array. now is:-1,2,1,0,1
code.js:113 pushed 1into array. now is:-1,2,1,0,1,1
我发现实现上述目标的代码要简单得多。但是,我正在尝试学习,但我还不了解方法末尾出了什么问题。逻辑上的缺陷在哪里?
答案 0 :(得分:1)
所以当前代码的问题是您使用break
,此处应使用return
if (num == tempArr[i]){
console.log("FOUND DOUBLE! random num = "+num+" IS ALREADY IN array:"+tempArr)
assignTemp(tempArr);
break; // <-- should be return instead
}
这样做的原因是,一旦找到了一个非唯一的数字,您就可以重新开始搜索下一个数字,但是中断将退出循环,并且在for循环之后,直接将num
添加到您的数组。因此,它将首先添加一个可能新的唯一编号,然后退出该循环,然后返回以退出您的第一个循环,然后添加非唯一编号;)
您还可以通过以下方式重写代码(我不知道您是否对某些JavaScript版本有任何要求,或者只允许使用for循环)
function randomRecep(){
return Math.floor((Math.random() * 3));
}
function assignTemp(tempArr){
const number = randomRecep();
if (tempArr.includes( number ) ) {
console.warn( `${number} exists in [${tempArr.join(', ')}]` );
return assignTemp(tempArr);
}
console.warn( `adding ${number} to [${tempArr.join(', ')}]` );
tempArr.push( number );
return tempArr;
}
const output = [];
// shouldn't call this more than the nr of output possibilities (and the pool here has 3 options)
assignTemp( output );
assignTemp( output );
assignTemp( output );
// we will always expect 0, 1, 2 in the output in some manner
console.log( output );