简体   繁体   中英

localStorage not storing more than one piece of data

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM