我在做一个小的抽风游戏。
当轮到电脑玩的时候,我让他选择一个随机数从一个数组中选择一个元素。
我的问题是,例如随机数将是3,但从数组中选择的元素将不是arr[3],而是arr[4]。
这是一个问题,因为如果选择的数字是数组的末尾,它将返回未定义的。
下面是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);
我的问题来自这样一个事实,即我在将数组元素推入新数组之前使用了splice。
下面是正确的javascript代码:
function computer(){
var ran = Math.floor(Math.random() * choice);
var res = grid[ran];
$('#' + res).html('O');
cpu.push(grid[ran]); // this line needs to be before having the element removed.
grid.splice(grid.indexOf(res), 1);
findElement(cpu);
choice -= 1;
console.log(ran);
console.log(cpu);
}
控制台日志只是在这里帮助我修复错误。
谢谢你的帮助!