How do I change a single value inside a localStorage item?

后端 未结 2 1301
不知归路
不知归路 2021-02-11 01:00

I have a set of items that get saved but I\'m trying to change a value after I retrieve it and before I pass it of to my php function. Is it possible to change just one item?

2条回答
  •  忘掉有多难
    2021-02-11 01:29

    localstorage does not return an array or an object. It can only store a string.

    The way people get around it, is to JSON.stringify() the array/object before passing it to setItem. Then, when retrieving it with getItem(), you run JSON.parse() on it.

    Assuming this is an object, and you've parsed it, you can modify your args variable before you send it along:

    args.type = 6;
    

    To ease all this, here's a little helper that you can call:

    var localstorage = {
        set: function (key, value) {
            window.localStorage.setItem( key, JSON.stringify(value) );
        },
        get: function (key) {
            try {
                return JSON.parse( window.localStorage.getItem(key) );
            } catch (e) {
                return null;
            }
        }
    };
    

    If you include this script, you can then set and get items through localstorage.get and localstorage.set, and it'll automatically convert it to & from JSON.

提交回复
热议问题