从localstorage中删除数组项 [英] Remove array item from localstorage

查看:349
本文介绍了从localstorage中删除数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在localstorage中存储了一个数组(解析为json)。
我把它拿回到一个对象中,从中删除了一些项目,我需要使用本地存储中的新值更新密钥。

I have an array i stored(parsed it as json) in localstorage. I got it back into an object, removed some items from it and i need to update the key with the new values in the local storage.

var counter = [0,1,2];
var count = counter[0];
var questions = localStorage.getItem('questions');///questions had been stored in local storage with another function
console.log(questions);
questions = $.parseJSON(questions);

if (questions != 0){
    $('.question').html(questions[count]['question']);
    var options = (questions[count]['options']);
    options.forEach(function (item) {
        $('.options').html(item);
    });
    var index = counter.indexOf(1);
    questions = questions.splice(index, 1);
    console.log(questions);
    localStorage.removeItem('questions);
    counter = counter.splice(index, 0);

现在,当我从本地存储中删除问题密钥时,整个问题数组将被删除,但是,我只需要删除传递的特定问题数组。

Now, when i remove the question key from the local storage, the whole question array is deleted, however, i only need to delete the particular question array that was passed.

推荐答案

不要删除密钥,只需再次设置新问题数组:

Instead of deleting the key, just set it again with the new questions array:

questions.splice(index, 1);
localStorage.setItem('questions', JSON.stringify(questions));

这篇关于从localstorage中删除数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆