数组随机值,​​无需在循环中重复数组

时间:2019-11-23 22:14:23

标签: javascript arrays object random arrayobject

如何使用JavaScript遍历数组中的所有条目?我有一个数组,我想要在arrRand变量中另一个随机数组列表,然后执行我的进一步代码。

 list1 = ['aceClub', 'twoClub'];
 list2 = ['fourDiamond', 'aceClub', 'fourHeart', 'twoDiamond'];
 list3 = ['aceHeart', 'aceClub', 'aceHeart', 'aceDiamond'];
 list4 = ['aceDiamond', 'fourSpade', 'twoClub', 'fourHeart'];
 list5 = ['fourClub', 'twoSpade' , 'twoHeart', 'aceDiamond'];
 list6 = ['twoHeart', 'twoDiamond' , 'twoSpade' , 'aceClub'];

 var arr = [list1,list2,list3,list4, list5,list6];

我希望以随机数的形式出现。

var arrRand = [list5,list6,list2,list4, list3,list1];
var arrRand = [list3,list2,list6,list5, list1,list4];
var arrRand = [list1,list5,list2,list4, list6,list2];

然后

if(arrRand[0] == list1){
   //mycode 
}
if(arrRand[1] == list2){
  //myCode
}
....

2 个答案:

答案 0 :(得分:1)

JavaScript中数组的标准随机播放似乎是Fisher-yates随机播放-from this answer

let list1 = ['aceClub', 'twoClub'];
let list2 = ['fourDiamond', 'aceClub', 'fourHeart', 'twoDiamond'];
let list3 = ['aceHeart', 'aceClub', 'aceHeart', 'aceDiamond'];
let list4 = ['aceDiamond', 'fourSpade', 'twoClub', 'fourHeart'];
let list5 = ['fourClub', 'twoSpade', 'twoHeart', 'aceDiamond'];
let list6 = ['twoHeart', 'twoDiamond', 'twoSpade', 'aceClub'];

let arr = [list1, list2, list3, list4, list5, list6];

let arrRand = shuffle(arr);
console.log(arrRand);

function shuffle(array) {
  let currentIndex = array.length;
  let temporaryValue;
  let randomIndex;

  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

答案 1 :(得分:0)

我认为您想要做的是对数组进行洗牌。您可以将sort方法与随机生成的数字一起使用,作为其比较功能:

 list1 = ['aceClub', 'twoClub'];
 list2 = ['fourDiamond', 'aceClub', 'fourHeart', 'twoDiamond'];
 list3 = ['aceHeart', 'aceClub', 'aceHeart', 'aceDiamond'];
 list4 = ['aceDiamond', 'fourSpade', 'twoClub', 'fourHeart'];
 list5 = ['fourClub', 'twoSpade' , 'twoHeart', 'aceDiamond'];
 list6 = ['twoHeart', 'twoDiamond' , 'twoSpade' , 'aceClub'];

 var arr = [list1,list2,list3,list4, list5,list6];

 const shuffle = arr => arr.sort(() => Math.random() - 0.5);

 console.log(shuffle(arr))   //different array order on each fn call
 console.log(shuffle(arr))
 ...