[当用户按下按钮并进行第一次随机播放时,如果要进行进一步的随机播放尝试,我希望再次显示第一个结果。
例如:第一次洗牌[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>
我将做一个称为记忆的变体。在这种情况下,我们只想确保只评估一次混洗。因此,第一次通过随机播放,然后存储结果(缓存)。下次调用它时,将仅返回缓存。
只要您不将此例程也应用于其他函数,它就可以正常工作,因为它只会保存一个缓存的值。有多种方法可以使这种方法更通用,您可以从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);
将结果放入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));
}