如何在用户按下刷新按钮时限制洗牌

how to restrict shuffling while user presses the refresh button

当用户按下按钮并进行第一次随机播放时,如果有进一步的随机播放尝试,我希望再次显示第一个结果。

例如: 第一次洗牌 [42, 37, 11, 2]; 进一步洗牌:[42、37、11、2](如果用户按下刷新按钮,我想再次显示相同的第一次洗牌结果 9

<script>
    var arr = [2, 11, 37, 42];
    arr = shuffle(arr);
    console.log(arr);

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

      // While there remain elements to shuffle...
      while (0 !== currentIndex) {
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
      }        
      return array;
    }
</script>

将结果放入sessionStorage;加载时,只有在无法从 sessionStorage 获取时才随机播放。类似于:

var arr, arrJSON;
arrJSON = sessionStorage.getItem('shuffledArray');
if (arrJSON) {
  arr = JSON.parse(arrJSON);
} else {
  arr = shuffle([2, 11, 37, 42)];
  sessionStorage.setItem('shuffledArray', JSON.stringify(arr));
}

我会做一种叫做记忆的变体。在这种情况下,我们只想确保我们只评估洗牌一次。所以第一次通过我们洗牌然后存储结果(缓存)。下次调用它时,它只会 return 缓存。

只要您不将此例程也应用于另一个函数,它就可以正常工作,因为它只会保存一个缓存值。有多种方法可以使它更通用,您可以先在 this link

阅读这种方法

function memoize(func) {
  var cache;
  return function() {
    if(cache) {
      return cache;
    }
    else {
      var val = func.apply(this, arguments);
      cache = val;
      return val;
    }
  };
}

var shuffle = memoize(function (array) {

  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
});

var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);
arr = shuffle(arr);
console.log(arr);
arr = shuffle(arr);
console.log(arr);