随机化数组中的对象

时间:2017-03-11 01:18:32

标签: javascript arrays random shuffle

每次arraybutton时,我都有一个clicked呈现25个图像/引脚,并且它只呈现array中的前25个。我希望它一次渲染25个引脚,但每次点击random时都希望它们为button

有人建议我使用此前设定的部分答案,但我无法弄清楚如何应用它或理解我所拥有的。

这是我被告知要使用的内容:

randomIndex = Math.floor(Math.random() * currentIndex);

将当前索引替换为我想要的array加上。长度。



var pinIdArray = ["448460075380400214", "554857616577037440", "129619295506364205"];					
var boardIdArray = [];
var showPins = [];
      
function(){
  res.render("suggested", {pins: showPins});




3 个答案:

答案 0 :(得分:1)

您可以使用Durstenfeld shuffle来重新排列数组,然后获取数组中的前25个元素。

function shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

var array = [];
for(var i = 0; i < 500; i ++) {
    array[i] = i;
}
console.log(shuffleArray(array).slice(0, 25));

答案 1 :(得分:1)

这是一个在Javascript中实现的函数,没有任何库。这也避免了洗牌,所以应该更快。

&#13;
&#13;
let pinIdArray = ["448460075380400214", "554857616577037440", "129619295506364205", "3403722138", "8005795986", "7717201977", "6689430878", "7705363504", "3827905985", "9133621064", "9162201846", "2655432017", "0197893312", "7220269979", "3218703261", "3478813716", "7445481990", "9806757977", "9357022147", "3492330721", "3504169963", "9259212333", "6574699545", "9727263383", "0016479256", "1624997250", "2083975447", "5683391989", "3466001901", "4660933902", "5216511997", "8820216343", "8583764035", "4563326839", "5201961267", "3429608185", "5007846054", "7437408815", "3472117054", "1545827364", "3152159572", "7913372317", "2550237417"];

function getRandomSubset(array, setSize) {
  let maxValue = array.length, tmpSet = new Set(), randomIndices;
  if (maxValue <= setSize) {
    randomIndices = [...Array(setSize).keys()];
  } else {
    while (tmpSet.size < setSize) {
      tmpSet.add(Math.floor(Math.random() * maxValue));
    }
    randomIndices = Array.from(tmpSet)
  }
  return randomIndices.map(index => array[index]);
}

//function(){
//  res.render("suggested", {pins: getRandomSubset(pinIdArray, 25)});

// Test
console.log("25 Random Elements:", getRandomSubset(pinIdArray, 25));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用pyautogui crashes whenever it clicks _.shuffle函数随机化/随机播放数组中的值。 Lodash _.shuffle函数使用Lodash's的版本。

var array = [1, 2, 3, 4];
var result = _.shuffle(array)
console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>