【问题标题】:localStorage differentiate between non-existent key and null valuelocalStorage 区分不存在的键和空值
【发布时间】:2021-11-19 01:30:08
【问题描述】:

在某些情况下,我需要在 localStorage 中存储一些“对象”为空的信息。但它不支持。

localStorage.setItem('tt', null);
const tt = localStorage.getItem('tt');
console.log(tt.length);
console.log(`tt is ${tt == null ? '' : 'NOT '}null`);

这段代码放到控制台:

4
tt is NOT null

为什么?

我可以调整我的逻辑,避免在存储中保存空对象,但在某些情况下,你想区分数据“对象的值是未知的”和“对象的值是空的”。

我应该为此使用另一个变量吗?

【问题讨论】:

  • 我认为你不需要保存空值。通常,如果您在 localStorage 上没有该项目,您将得到一个 undefined/null

标签: javascript angular local-storage


【解决方案1】:

localStorage只能存储字符串键/值对;因此nulllocalStorage中设置项时将转换为字符串形式('null')。

null比较时使用严格的类型检查将解决问题:

localStorage.setItem('tt', null);
const tt = localStorage.getItem('tt');
console.log(`tt is ${tt === null ? '' : 'NOT '}null`);

或者,您可以使用in operator 来检查密钥是否存在:

console.log(`tt is ${'tt' in localStorage ? 'NOT' : ''} null`);

【讨论】:

    【解决方案2】:

    基于DocumentationgetItem的返回值是一个DomString

    A DOMString containing the value of the key. If the key does not exist, null is returned.

    如果要说 null,则需要使用 JSON.stringifyJSON.parse

    localStorage.setItem('tt', JSON.stringify(null));
    const tt = JSON.parse(localStorage.getItem('tt'));
    
    console.log(`tt is ${tt == null ? '' : 'NOT '}null`);
    
    

    【讨论】:

      【解决方案3】:

      根据文档,setItem 接收将 null 转换为字符串“null”的 DOMString。这就是为什么当你保存 null 时你会得到长度 4。

      https://developer.mozilla.org/en-US/docs/Web/API/DOMString

      某些接受 DOMString 的 Web API 有一个额外的遗留行为,其中传递 null 字符串化为空字符串,而不是通常的“null”。

      如果你想设置 null 我会使用 removeItem("tt") 来获取 null 值。

      【讨论】:

        猜你喜欢
        • 2013-07-26
        • 2011-12-25
        • 2013-11-27
        • 2016-05-09
        • 2022-10-04
        • 1970-01-01
        • 2015-12-04
        • 2014-09-24
        • 2021-05-11
        相关资源
        最近更新 更多