[英]Random value on an array
我想在數組上生成一個隨機值。 但是每次單擊時,數組都會獲得一個新值,所以我不想獲得一個已經在數組上具有值的隨機值。 簡而言之,我需要隨機獲取數組的空值。
這是代碼的一小部分。 我的數組上有9個值,一開始它們都是空的。
var gameCase = ['', '', '', '', '', '', '', '', ''];
var randomValue = gameCase[VALUE_EMPTY*][Math.round(Math.random()*gameCase.length)];
*這是我不知道該怎么做的部分。
有幾種方法可以解決此問題:
方法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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.