【问题标题】:if localStorage key value doesn't exist如果 localStorage 键值不存在
【发布时间】:2013-07-26 16:50:42
【问题描述】:

如果没有 localStorage 键值,我会尝试隐藏我的 div。

通过下面的行,我实现了仅在 localStorage 键完全删除时隐藏 div,但如果 localStorage 键没有任何值只是 [] 则需要执行相同操作。

 window.localStorage.getItem('items') === null

它将如何执行?

【问题讨论】:

    标签: html local-storage


    【解决方案1】:

    您可以使用OR 运算符|| 添加所需条件

    var items = window.localStorage.getItem('items')
    
    if (items === null || items.length === 0)
    {
        // items is null, [] or '' (empty string)
    }
    

    如果您还必须在某处检查 undefined,您可以将 === null 更改为 == null 或使用类似这样的额外条件进行扩展

    if (items === undefined || items === null || items.length === 0)
    {
        // items is undefined, null, [] or '' (empty string)
    }
    

    编辑:这是您可以直接获取数组的方法

    var items = JSON.parse(window.localStorage.getItem('items'))
    
    if (items === null || items.length === 0)
    {
        // items is null or []
    }
    

    【讨论】:

    • 谢谢 Ma3x,但是当 [] 在值字段中时它不起作用,也许它接受 [] 作为字符?
    • 是的,我想我已经用 if (items === undefined || items === null || items.length
    • @qqruza:如果您将数组编码为 JSON 字符串,那么您可以像这样比较 items == '[]' 或先使用 var itemsArray = JSON.parse(items) 解析,然后使用 itemsArray.length === 0
    • @PRMan:你的意思是if(!items),因为 OP 想知道什么时候没有数组或者什么时候数组为空?不同之处在于空数组,它不满足if(!items) 条件。
    【解决方案2】:

    简单地说:

    if (!localStorage.nameOfYourLocalStorage) {
        // do the following if the localStorage.nameOfYourLocalStorage does not exist
    }
    

    一个有用的例子:

    if (!localStorage.nameOfYourLocalStorage) {
        localStorage.nameOfYourLocalStorage = defaultValue;
    }
    

    这里脚本会检查localStorage名称是否不存在,如果不存在,则使用默认值创建。

    如果您希望它在它确实存在时起作用,您可以在 if 块之后添加 else 以继续,或者删除 '!' 来自 if 块 条件。

    【讨论】:

      【解决方案3】:
      Storage.prototype.has = function(key) {
        return (key in this && !(key in Storage.prototype));
      };
      

      【讨论】:

        猜你喜欢
        • 2021-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2012-03-22
        • 2022-01-04
        • 2021-09-24
        • 1970-01-01
        相关资源
        最近更新 更多