var globalScope = {}
function generateNum() {
globalScope.genNum = [];
for (var i = 0; i < 4; i++) {
var numEl = Math.floor((Math.random() * 9)+1);
globalScope.genNum.push(numEl);
}
return globalScope.genNum;
}
大家好。我刚刚开始学习 JS,我的硬件是创建一个 4 位数组,其中包含从 1 到 9 的不重复数字(对于游戏 Bulls and Cows)。但我不知道如何实现检查这个数组是否有重复的数字。请有人帮忙。提前致谢
最佳答案
或者,您可以使用包含从 0
到 9
的所有数字的源数组,每次从源中选择并删除其中一个:
function genNum(){
var arr = [], // target array
source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], // source array
sourceLen = source.length,
i, r;
for (i=0; i<4; i++) {
r = Math.floor(Math.random()*(sourceLen-i)); // pick a random index
// remove it from the source and add it to the target
arr.push(source.splice(r, 1)[0]);
}
// return it
return arr;
}
在 MDN 上了解有关 .splice
方法的更多信息.
关于javascript - 生成一个4位数组,其中包含不重复的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24722489/