【发布时间】:2019-01-02 20:31:34
【问题描述】:
所以我正在开发一个基于 JavaScript 的简单网络游戏。目标是猜测 X 位随机数。这意味着随机数可以是 4、5 位数字,最多可以是您想要的任何数字。您实际上可以在 www.juegodescifralo.com 上玩游戏(这是西班牙语,对此感到抱歉)。
用户输入一个以数组形式存储的数字。随机数也作为数组生成。两个数组中的单个数字都可以重复。
存在三种可能的“值/数字”:“好”的数字是您选择的与随机数组中的数字位置相同的数字。比如:
随机数组为:1457
用户输入为:6851
数字 5 是一个“好”的数字,因为它位于相同的位置。然后是第二种“值”,即“常规”。这意味着它们在随机数内,但不在同一位置。在此示例中,数字 1 将是“常规”值。第三种是“坏”的,甚至不在随机数组中。
我开发的功能如下:
function checkNumbers(randomArray, myArray, good, regular, bad) {
for (var x = 0; x < randomArray.length; x++) {
var posRepetido = randomArray.indexOf(myArray[x]); //Is current number inside random array?
if (posRepetido == -1) { //It's not inside
console.log("number " + myArray[x] + "is not inside");
bad++;
} else { //It's inside
regular++;
if (myArray[x] == randomArray[x]) { //If it's the same number...
console.log("number " + myArray[x] + "is in the correct position");
good++;
regular--;
} else { //If it's not the same number
if (randomArray[posRepetido] != myArray[posRepetido]) {
console.log("number " + myArray[x] + "is inside but not in the same position");
} else {
console.log("number " + myArray[x] + "is not inside");
}
}
}
}
var obj = { //Return object for accessing later, to show feedback to the user.
good: good,
regular: regular,
bad: bad
};
return obj;
}
代码有点错误。当随机数组中有重复项,其中一个被标记为好,那么另一个(即使它存在于用户输入中)将被设置为坏,而不是应有的规则。
事情变得更加复杂,因为您应该能够与任意数量的数字对战。所以我应该能够毫无“问题”地猜出一个 20 位数字。
您可以在 www.juegodescifralo.com 上自己玩
我该怎么办?任何想法如何更轻松地访问数组数据?非常感谢!
【问题讨论】:
标签: javascript arrays loops