从数组中选择随机项Remove It, Restart Once Array is Empty

Select Random Item from Array & Remove It, Restart Once Array is Empty

本文关键字:Restart Once Array Empty is It Remove 数组 选择 随机      更新时间:2023-09-26

我试图设置从数组中选择一个随机项目。一旦被选中,它需要从数组中删除,这样它就不会再次被选中。最后,清空数组后,需要重新启动进程。我试图这样做使用sessionStorage,因为我需要保持跟踪哪个随机项目被选中。

// Get array from sessionStorage
myArray = JSON.parse(sessionStorage.getItem("array"));
// If array does not exist in sessionStorage, set it
if (myArray === null) {
  sessionStorage.setItem("array", JSON.stringify(["apple", "orange", "banana"]));
// If array exists in sessionStorage, use it to get random item and empty it from array
} else {
  var randomItem = myArray[Math.floor(Math.random() * myArray.length)];
  console.log(randomItem);
  console.log(myArray.splice(randomItem, 1));
}

我的JSFiddle可以在这里看到

编辑:在这里更新了我的工作。最后,该数组将被清空并重新启动。

这可能不会运行在这个沙箱(使用localstore),但我认为它应该工作,如果你尝试它。

// -------------------------------
// see: http://stackoverflow.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);

一个更简单的版本[with _shuffle() from above]可能只是:

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"]);

我认为你所遇到的问题是由于你正在传递你从数组得到的值splice()函数,当它实际上是期望一个索引。签出文档页面。所以你要做的是:

// Get array from sessionStorage
myArray = JSON.parse(sessionStorage.getItem("array"));
// If array does not exist in sessionStorage, set it
if (myArray === null) {
  sessionStorage.setItem("array", JSON.stringify(["apple", "orange", "banana"]));
// If array exists in sessionStorage, use it to get random item and empty it from array
} else {
  //get random index of item to remove
  var randomIndex = Math.floor(Math.random() * myArray.length);
  //remove the item at that index
  myArray.splice(randomIndex, 1); //this returns an array containing the removed item, so you can capture it if you like
}