我想在数组上生成一个随机值。但是每次单击,数组都会获得一个新值,所以我不想得到一个已经在数组上有值的随机值。简而言之,我需要随机获取数组的空值。
这是代码的一小部分。我的数组中有9个值,并且在开始时它们都是空的。
var gameCase = ['', '', '', '', '', '', '', '', ''];
var randomValue = gameCase[VALUE_EMPTY*][Math.round(Math.random()*gameCase.length)];
*这是我真不知道该怎么做的部分。
答案 0 :(得分:3)
有几种方法可以解决这个问题:
方法1:继续生成随机索引,直到它指向空值
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/