我试图设置从数组中选择一个随机项。选择后,需要从阵列中删除它,以便不再选中它。最后,一旦清空阵列,该过程需要重新启动。我尝试使用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 here 。
修改:更新了我的作品 here 。最终清除阵列并重新启动。
答案 0 :(得分:2)
这可能不会在这个沙箱中运行(使用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);
更加简单的骨骼版本[上面带有_shuffle()]可能只是:
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"]);
答案 1 :(得分:1)
我认为你遇到的问题是由于你实际上在期望一个索引时传递了你从数组得到的值(splice()函数)。查看docs页面。所以你要做的是:
// 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
}