我正在构建一个小型井字游戏。
当轮到计算机玩时,我让他选择一个随机数来从数组中选择一个元素。
我的问题是,例如,随机数为 3,但从数组中选取的元素不会是 arr[3],而是 arr[4]。
这是一个问题,因为如果选取的数字是数组的末尾,它将返回 undefined。
这是 JavaScript 代码:
var grid = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9'];
var choice = 9;
function myFunction(clicked_id){
$('#' + clicked_id).html('X');
grid.splice(grid.indexOf(clicked_id), 1);
choice -= 1;
setTimeout(computer, 1000);
player.push(clicked_id);
findElement(player);
console.log(player);
console.log(grid);
console.log(grid.length)
}
function computer(){
var ran = Math.floor(Math.random() * choice);
var res = grid[ran - 1];
$('#' + res).html('O');
grid.splice(grid.indexOf(res), 1);
cpu.push(grid[ran]);
findElement(cpu);
choice -= 1;
console.log(ran);
console.log(cpu);
}
以下是控制台日志中将记录的内容: [“item1”] -> 我点击的内容
["item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"] -> 使用拼接后的新修改数组。
8 -> 新数组长度
5 - 计算机选取的随机数
["item8"] -> 计算机在数组中选取的元素 (arr[6])
“item6”是井字游戏中选中的复选框。
这是我的 codepen 的链接,可以查看正在运行的代码。
https://codepen.io/nico3d911/pen/odvmPR?editors=0001
感谢您的帮助!
最佳答案
请注意,JS 使用从零开始的索引 - 因此 item1 的索引为 0,item2 的索引为 1 等等,直到 item9 的索引为 8。
Math.random() 返回一个 0 到 1 之间的数字(包括 0 和 1),这意味着 Math.random() * 9 可以返回超出范围的 9 - 对于长度为 9 的数组,最大索引为 8。
更改上限应该可以解决您的问题:
var ran = Math.floor(Math.random() * (choice - 1))
一个小问题:grid.indexOf(res)
始终等于 ran
,您可以只使用 grid.splice(ran, 1);
关于javascript - math.floor 和 math.radom 相差一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008694/