Javascript 如果语句为false,则再次随机化数字
也这样做,但仍然超过堆栈大小,并且仍然与前面的操作相同。使用while语句Javascript 如果语句为false,则再次随机化数字,javascript,random,Javascript,Random,也这样做,但仍然超过堆栈大小,并且仍然与前面的操作相同。使用while语句 function computerLogic(array) { function random() { var rand = Math.floor(Math.random() * 9); var result = (array[rand] === computerChoice) || (array[rand] === playerChoice) ? random(): (function(rand) {
function computerLogic(array) {
function random() {
var rand = Math.floor(Math.random() * 9);
var result = (array[rand] === computerChoice) || (array[rand] === playerChoice) ?
random(): (function(rand) {
array[rand] = computerChoice;
grid.item(rand).innerHTML = computerChoice;
})(rand);
}
random();
}
我在想,但是它如何再次检查第一个If语句??编辑你想让我把它放在if语句中还是代替if语句?它现在只是随机数,而不是更新电路板。你需要将if-else语句移动到while循环中(在
rand=Math.floor(Math.random()*9);
)。如果(array[rand]==playerChoice)| |(array[rand]==computerChoice)
,则说返回代码>。这将退出if语句并返回顶部,其中rand=Math.floor(Math.random()*9)代码>将再次调用。在else if和else中添加break代码>结束,这将退出while循环。while((数组[rand]==playerChoice)| |(数组[rand]==computerChoice))我是这样做的,但我觉得我的while语句失败了。如果数组[random]不等于computerChoice或playerChoice,while循环将不会执行,因此它的想法是错误的,或者我不理解它。
function computerLogic(array) {
function random() {
var rand = Math.floor(Math.random() * 9);
var result = (array[rand] === computerChoice) || (array[rand] === playerChoice) ?
random(): (function(rand) {
array[rand] = computerChoice;
grid.item(rand).innerHTML = computerChoice;
})(rand);
}
random();
}
while((array[rand] === playerChoice)||(array[rand] === computerChoice)) {
rand = Math.floor(Math.random() * 9);
}