我想使用本地存储来进行这个“随机”选择...随机的,但仅基于数组中的其余对象。
因此,如果选择了3个-那么随机发生器将在下一个选择中计数,依此类推,然后-当所有4个对象都被使用时,重置并重复整个过程。我还没有太多地使用本地存储-所以我正在寻找一些最优雅的方式来做这件事的建议。
var sceneChoices = [
skylineOne = {
skyline: '01',
ID: '9YwX81KAqdk'
},
skylineTwo = {
skyline: '02',
ID: 'bqJwMYzsmHU'
},
skylineThree = {
skyline: '03',
ID: 'DwNTvj61VQw'
},
skylineFour = {
skyline: '04',
ID: '2cg-Uc556-Q'
}
];
if ( typeof(Storage) !== 'undefined' ) { // local storage style
var randomSunset = sceneChoices[Math.floor(Math.random() * sceneChoices.length)];
} else { // regular style
var randomSunset = sceneChoices[Math.floor(Math.random() * sceneChoices.length)];
}
var sunsetName = randomSunset.skyline;
var youTubeId = randomSunset.ID;(很快就写出来了……而且它是不正确的-如下所述)
我想我真的想要一个这样的数组。
var sunsetChoices = [
{
ID: '01',
videoKey: '9YwX81KAqdk'
},
{
ID: '02',
videoKey: 'bqJwMYzsmHU'
},
{
ID: '03',
videoKey: 'DwNTvj61VQw'
},
{
ID: '04',
videoKey: '2cg-Uc556-Q'
}
]; 发布于 2015-05-13 08:26:39
您可以将剩余的选择键存储在localStorage中,每次加载页面时,您都会从剩余的选项中随机选择一项,然后更新剩余的选项。
工作演示:http://jsfiddle.net/jfriend00/rr75868q/。每次运行jsFiddle时,它都会显示一个不同的sceneChoice项,直到全部显示完毕,然后再重新开始。
var sceneChoices = {
skylineOne: {
skyline: '01',
ID: '9YwX81KAqdk'
},
skylineTwo: {
skyline: '02',
ID: 'bqJwMYzsmHU'
},
skylineThree: {
skyline: '03',
ID: 'DwNTvj61VQw'
},
skylineFour: {
skyline: '04',
ID: '2cg-Uc556-Q'
}
};
// select a random object that has not been used
var items = localStorage.getItem('remainingKeys');
if (items) {
try {
items = JSON.parse(items);
} catch(e) {
// no nothing, items will still be falsey
// so it will get initialized in the next code block
}
}
if (!items || !items.length) {
// nothing stored, so initialize with all keys
items = Object.keys(sceneChoices);
}
var index = Math.floor(Math.random() * items.length);
var randomObj = sceneChoices[items[index]];
// now remove the selected item from the items array of keys
// and then store back to localStorage
items.splice(index, 1);
localStorage.setItem('remainingKeys', JSON.stringify(items));注意:我必须修复sceneChoices的声明,它不是您拥有的合法Javascript的方式。
https://stackoverflow.com/questions/30203404
复制相似问题