localStorage not storing more than one piece of data

后端 未结 1 2017
时光说笑
时光说笑 2021-01-27 12:12

I\'m trying to store multiple pieces of data in localStorage. However, only one piece is being stored and I can\'t figure out why. Here\'s the code



        
相关标签:
1条回答
  • 2021-01-27 12:57

    You're overwriting lastname every time you call setItem, so the last one (saving "Jones") wins.

    If you want to save more than one item, either:

    1. Use a different key (lastname1, lastname2, ...), or

    2. Store a string in some format you can parse into individual items, for instance an array that you JSON.stringify when storing and JSON.parse when loading


    Side note: Sadly, that typeof check is not adequate to determine whether you can use localStorage, because on some browsers in private browsing mode, typeof will say it's there but it'll throw an error when you try to save something. The only way to know for sure is to actually try to save something:

    // Once on page load
    const canUseStorage = typeof localStorage !== "undefined" && (() {
        const key = "_test_storage";
        const now = String(Date.now());
        try {
            localStorage.setItem(key, now);
            const flag = localStorage.getItem(key) === now;
            try {
                localStorage.removeItem(key);
            } catch (e) {
            }
            return flag;
        } catch (e) {
            return false;
        }
    })();
    
    // Then use `canUseStorage` as necessary to decide if you can use it
    

    (Also note that typeof is an operator, not a function. No need for parens around its operand.)

    0 讨论(0)
提交回复
热议问题