0

我想在数组上生成一个随机值。但是每次点击,数组都会获得一个新值,所以我不想得到一个在数组上已经有值的随机值。简而言之,我需要随机获取数组的空值。

这是代码的一小部分。我的数组上有 9 个值,一开始它们都是空的。

var gameCase = ['', '', '', '', '', '', '', '', ''];
var randomValue = gameCase[VALUE_EMPTY*][Math.round(Math.random()*gameCase.length)];

*这是我真的不知道该怎么做的部分。

4

1 回答 1

3

有几种方法可以解决这个问题:

方法一:不断生成随机索引,直到它指向一个空值

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/

于 2013-04-13T15:51:24.810 回答