有几种方法可以解决这个问题:
方法一:不断生成随机索引,直到它指向一个空值
var gameCase = ['', '', '', '', '', '', '', '', ''];
var randomIndex = Math.round(Math.random()*gameCase.length) % emptyCases.length;
var randomValue = gameCase[randomIndex];
// while we haven't found the empty value
while (randomValue !== '') {
// keep on looking
randomIndex = Math.round(Math.random()*gameCase.length % emptyCases.length);
randomValue = gameCase[randomIndex];
}
// when we exit the while loop:
// - randomValue would === ''
// - randomIndex would point to its position in gameCase[]
方法 2:有一个第二个数组来跟踪数组的哪些索引gameCase
具有空值
var gameCase = ['', '', '', '', '', '', '', '', ''];
var emptyCases = [0,1,2,3,4,5,6,7,8];
if (emptyCases.length > 0) {
// generate random Index from emptyCases[]
var randomIndex = emptyCase[Math.round(Math.random()*emptyCase.length) % emptyCases.length];
// get the corresponding value
var randomValue = gameCase[randomIndex];
// remove index from emptyCases[]
emptyCases.splice(randomIndex, 1);
}
方法#2 在某种意义上更有效,因为您没有浪费时间来生成/猜测随机索引。对于方法#1,您需要一种方法来检查是否有任何空值留在其中gameCase[]
,否则您可能会在无限循环中永远生成/猜测。
更多:当您设置值时,gameCase[]
您需要emptyCases[]
相应地更新以准确反映以下状态gameCase[]
:
var gameCase = ['', '', '', '', '', '', '', '', ''];
var emptyCases = [0,1,2,3,4,5,6,7,8];
/* Update a value in gameCase[] at the specified index */
var setGameCaseValue = function(index, value) {
// set value for gameCase[]
gameCase[index] = value;
if (value !== '') { // we're setting a value
// remove that index from emptyCases[]
emptyCases.splice(emptyCases.indexOf(index), 1);
} else { // we're setting it back to empty string
// add that index into emptyCases[] that refers to the empty string in gameCase[]
emptyCases.push(index);
}
};
setGameCaseValue(2, 'null');
// gameCase now has ['','','null','','','','','','']
// emptyCases now has [0,1,3,4,5,6,7,8]
setGameCaseValue(0, 'null');
// gameCase now has ['null','','null','','','','','','']
// emptyCases now has [1,3,4,5,6,7,8]
setGameCaseValue(5, 'null');
// gameCase now has ['null','','null','','','null','','','']
// emptyCases now has [1,3,4,6,7,8]
setGameCaseValue(7, 'null');
// gameCase now has ['null','','null','','','null','','null','']
// emptyCases now has [1,3,4,6,8]
见小提琴:http: //jsfiddle.net/rWvnW/1/