且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从阵列&中选择随机项.删除它,在数组为空后重新启动

更新时间:2022-04-18 23:31:36

这可能无法在此沙箱中运行(使用localstore),但我认为如果您尝试过,它应该可以工作.

This probably will not run in this sandbox (use of localstore), but I think it should work if you tried it.

// -------------------------------
// see: http://***.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
// -------------------------------
function _shuffle (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;
}
// -------------------------------

// -------------------------------
// Get the next "random" item.
// -------------------------------
var randomItem  = (function(allItems){
  var _key = "array";
  var _currentItems = [];

  try {
    _currentItems = JSON.parse(localStorage.getItem(_key) || "[]");
  } catch (e) {
    _currentItems = [];
  }

  if (!Array.isArray(_currentItems) || _currentItems.length === 0 ) {
    console.log("resetting");
    _currentItems = _shuffle(allItems.slice());
  }

  var _selectedItem = _currentItems.pop();
  localStorage.setItem(_key, JSON.stringify(_currentItems));

  return _selectedItem;
})(["apple", "orange", "banana"]);
// -------------------------------

console.log(randomItem);

一个更裸露的版本[从上面带有_shuffle()]可能只是:

A more bare bones version [ with _shuffle() from above ] might be just:

var nextItem  = (function(all){
  var _key = "array";
  var _current = JSON.parse(localStorage.getItem(_key) || "[]");
  if (_current.length === 0) { _current = _shuffle(all.slice()); }

  var _selected = _current.pop();
  localStorage.setItem(_key, JSON.stringify(_current));

  return _selected;
})(["apple", "orange", "banana"]);