数组中的“随机”对象,直到所有使用时才重复 - 使用本地存储

时间:2015-05-13 00:00:38

标签: javascript local-storage

我想使用本地存储来进行“随机”选择...随机,但仅基于数组中剩余的对象。

因此,如果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'
    }
]; 

1 个答案:

答案 0 :(得分:1)

您可以将剩余的选择键存储在localStorage中,每次加载页面时,从剩余的选项中选择一个随机项,然后更新剩余的选项。

工作演示:style。每次运行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。