开发者问题收集

数组上的随机值

2013-04-13
181

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

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

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

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

1个回答

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

方法 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/

Amy
2013-04-13