0

大家
好 不知道如何以随机方式从数组中获取元素而不重复。这是我的代码:

var letters = [ "A", "A", "B", "B", "C", "C", "D", "D", "E", "E",
           "F", "F", "G", "G", "H", "H", "I", "I", "J", "J" ],
cards = document.getElementsByClassName( "cards" ),
cardBoxes = document.getElementsByClassName( "card-boxes" );


//generate random number
function randomNum( nums ) {
 return Math.floor( Math.random() * nums.length );
}


//hide letter behind card in random way
function hideLetter() {
 for ( var i = cards.length - 1; i >= 0; i-- ) { 
   var randomLetter = letters[ randomNum(letters) ];
   cards[i].textContent = randomLetter;
 };
}
hideLetter();

我以随机方式获取元素,但 Math.random 会重复自己。我想我必须写一些 if 语句,这将检测元素是否被取了两次,但不知道该怎么做。寻求建议。谢谢。

这里 Codepen 的问题http://codepen.io/Kuzyo/pen/vdlai

4

4 回答 4

2

确定的方法是在使用后从数组中删除元素。这样就不会重复了

于 2013-07-27T16:31:24.683 回答
2

随机化你的数组,然后遍历随机数组。这具有通常的“使用随机索引时删除元素”的好处,同时保留序列以防您需要依赖于相同随机排序的重复操作:

function randomize(array) {
  var copy = array.slice(),
      random = [],
      element, pos;
  while(copy.length>0) {
    pos = (Math.random()*copy.length) | 0; // bit operation forces 32-bit int
    subarray = copy.splice(pos, 1);
    random.push(subarray[0]);
  }
  return random;
}

var letters = [ "A", "A", "B", "B", "C", "C", "D", "D", "E", "E",
       "F", "F", "G", "G", "H", "H", "I", "I", "J", "J" ],
    randomLetters = randomize(letters);

randomLetters.forEach(function(letter) {
  // create a card for this letter
});

// do we need it again, in a new random fashion?
// then we can simply call this:
randomLetters = randomize(letters);
于 2013-07-27T16:31:33.183 回答
1

这是我的版本,带有生成器。返回的函数makeRandomGenerator将返回 的随机、非重复成员inputArray。使用完所有元素后,它将返回undefined.

function shuffle(array) {
  return array.sort(function() {
    return Math.random() > 0.5 ? 1 : -1;
  });
}

function makeRandomGenerator(inputArr) {
  var arr = inputArr.slice(0);
  shuffle(arr);

  return function() {
    return arr.pop();
  }
}

使用:

var letterGenerator = makeRandomGenerator(letters);

function hideLetter() {
 for ( var i = cards.length - 1; i >= 0; i-- ) { 
   var randomLetter = letterGenerator();
   if (randomLetter === undefined) {
     return;
   }
   cards[i].textContent = randomLetter;
 };
}
hideLetter();
于 2013-07-27T16:41:38.333 回答
0

随机化数组并从数组中移出值:

var letters   = [ "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F", "G", "G", "H", "H", "I", "I", "J", "J" ],
    cards     = document.getElementsByClassName( "cards" ),
    i         = letters.length, j, temp;

while ( --i ) {
    j = Math.floor( Math.random() * (i - 1) );
    temp = letters[i];
    letters[i] = letters[j];
    letters[j] = temp;
}

for ( var i = cards.length; i--; ) { 
     cards[i].innerHTML = letters.shift();
}

小提琴

于 2013-07-27T16:36:55.590 回答