localStorage not storing more than one piece of data

我的梦境 提交于 2020-01-30 11:48:45

问题


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

<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<div id="result2"></div>
<script>
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("lastname", "Smith");
    // Retrieve
    document.getElementById("result").innerHTML = 
    localStorage.getItem("lastname");
}
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("lastname", "Jones");
    // Retrieve
    document.getElementById("result2").innerHTML = 
    localStorage.getItem("lastname");
}
</script>
</body>
</html>

In Chrome Developer tools, under the application tab "Jones" is stored but "Smith" is not. I have checked similar questions, but none seem to provide a specific solution.


回答1:


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.)



来源:https://stackoverflow.com/questions/53304747/localstorage-not-storing-more-than-one-piece-of-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!