使用本地存储创建收藏夹列表

时间:2017-03-18 22:21:21

标签: javascript jquery local-storage

我正在尝试实现一个收藏夹列表,该列表获取用户正在查看的当前游戏的ID。到目前为止,我有这个:

$('#favouriteBtn').click(function(){
    currentAddFav();
});

function currentAddFav(){
    if(localStorage.getItem('favourites')){//If there are favourites
        var storage = JSON.parse(localStorage['favourites']);
        for (var i = 0;i <= storage.length;i++){
            if(storage[i] == currentGame.id){//Id already stored, we dont want a duplicate id so ignore
                console.log('id already stored');
                break;
            }
            else{//game id doesn't exist in storage so add the id to storage
                storage.push(currentGame.id);
                localStorage.setItem('favourites', JSON.stringify(storage));
                console.log('must be a new id?');
            }
        }
    }else{//No favourites in local storage, so add new
        var favArray= [];
        favArray.push(currentGame.id);
        localStorage.setItem("favourites", JSON.stringify(favArray));
        console.log('New favourites list');
    }

}

如果我尝试添加新的收藏夹,它会起作用,如果我尝试添加首次添加到列表中的相同收藏夹,它可以正常工作。然后,如果我尝试添加与首次添加的不同的收藏夹,则本地存储中的数组允许我继续向其添加新的ID。

1 个答案:

答案 0 :(得分:1)

你的循环错误

for (var i = 0;i <= storage.length;i++){

对存储中的每个项执行if或else的情况。你想要的是:

if (storage.indexOf(currentGame.id) == -1) { 
  # not found
  storage.push(currentGame.id);
  localStorage.setItem('favourites', JSON.stringify(storage));
} else {
  # found
  console.log('item already in favorites')
}