localStorage不能存储多个数据

localStorage不能存储多个数据

本文介绍了localStorage不能存储多个数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在localStorage中存储多个数据.但是,只存储了一件,我不知道为什么.这是代码

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>

在Chrome开发者工具中,应用程序"标签下存储了琼斯",但未存储史密斯".我检查了类似的问题,但似乎没有一个提供特定的解决方案.

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.

推荐答案

每次调用 setItem 时,您将覆盖 姓氏,因此最后一个(保存"Jones" )获胜.

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. 使用其他密钥( lastname1 lastname2 ,...)或

以某种格式存储字符串,您可以将其解析为单个项目,例如,存储时为 JSON.stringify 的数组,加载时为 JSON.parse 的数组

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


旁注:遗憾的是, typeof 检查不足以确定您是否可以使用 localStorage ,因为在某些浏览器中,处于私有浏览模式的 typeof 会说它在那里,但是当您尝试保存内容时会抛出错误.唯一可以确定的方法是实际尝试保存一些东西:


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

(还要注意, typeof 是运算符,而不是函数.不需要在其操作数周围加括号.)

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

这篇关于localStorage不能存储多个数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:51