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