Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用本地存储创建收藏夹列表_Javascript_Jquery_Local Storage - Fatal编程技术网

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

Javascript 使用本地存储创建收藏夹列表,javascript,jquery,local-storage,Javascript,Jquery,Local Storage,我正在尝试实现一个收藏夹列表,该列表获取用户正在查看的当前游戏的id。到目前为止,我有: $('#favouriteBtn').click(function(){ currentAddFav(); }); function currentAddFav(){ if(localStorage.getItem('favourites')){//If there are favourites var storage = JSON.parse(localStorage['

我正在尝试实现一个收藏夹列表,该列表获取用户正在查看的当前游戏的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。

您的循环是错误的

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

你的问题是什么,失败的是什么?@niklas基本上我想允许用户只向数组中添加一次收藏夹,我想避免重复ID,我目前获得重复ID,每次单击时都会触发循环下的if和else语句,这似乎解决了我的问题,谢谢!我们基本上是说,如果id不出现在数组中;加上它?是的。再次查看您的循环,思考当您的数组中有项目[2,3,4]且currentGame.id=4时会发生什么,您将执行if…else。。。三次,它将击中else案例两次项目2和3,然后击中if案例一次项目4。因此,4将被再添加两次到你的数组中,否则我的循环将对它迭代的每个数字执行操作,直到它达到目标?我建议你看看它,在你的头脑中或在一张纸上用不同的id数组和当前的game.id s玩它
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')
}