【问题标题】:Javascript localstorage condition not responding [duplicate]Javascript本地存储条件没有响应[重复]
【发布时间】:2018-11-29 08:52:42
【问题描述】:

我正在测试是否存在本地存储密钥。

所以首先我做了一个 console.log 来查看值的内容...

console.log(localStorage.getItem('mykey'));

这会返回null

所以我这样做是为了一个条件:

if (localStorage.getItem('mykey') === null) {
    console.log('It is null');
}

但是虽然我知道它是 null 它没有显示:

console.log('It is null');

可能是什么问题?

【问题讨论】:

  • 我可以通过将项目设置为"null" 来重现这一点,因为"null" 是一个字符串并且不同于null
  • 只需做if (!localStorage.getItem('mykey')) {...}
  • 我的意思是没有引号的“null”......我会编辑问题
  • 您在测试期间运行了setItem('mykey', ...),现在密钥存在。
  • 用localstorage进行CRUD操作需要时间stackoverflow.com/questions/23677373/…

标签: javascript local-storage


【解决方案1】:

更新

原来贴的localStorage.getItem('mykey') === null实际上在Chrome上返回true,所以可能是浏览器相关的问题。

因此,通过使用双等号 == 的第一个建议解决方案,可能会获得更好的跨浏览器支持,尽管第 2/3 个选项可能会更好。

如果键不存在,则返回值为object,即null,与null 的类型不同(===)

要么放下一个=(它会自动施放),它就会起作用

if (localStorage.getItem('mykey') == null) {
  console.log('It is null');
}

或者干脆做类似的事情,例如

if (!localStorage.getItem('mykey')) {
  console.log('It is null');
}

或 (as shown here) 可能会更好(实际上可能是骗子)

if (!localStorage.hasOwnProperty('mykey')) {
  console.log('It is null');
}

【讨论】:

  • 我不认为第一个建议是正确的。 localStorage.getItem('randomkey') === null 为真(在 Chromium 66 上测试)
  • @AurélienBottazini 对于版本 67.0.3396.87(官方版本)(64 位),它也返回 true ... 嗯,将更新我的答案,因为它看起来可能是浏览器问题。感谢您的评论
  • @AurélienBottazini 用可能更合适的内容更新了我的答案。
【解决方案2】:

标识 (===) 运算符检查两个操作数的值和数据类型是否相等或相同。也就是说,

var a = 2;
if (a === '2') 

- 将返回 false,因为 a 是整数而 '2' 是字符串。在哪里,

if (a == 2)

- 将返回 true,因为 '==' 运算符不强制数据类型相等。

因此,为了处理所有情况,例如 localStorage 中缺少键或显式设置为 null,您应该使用 '==' 运算符。

【讨论】:

    【解决方案3】:

    关于正在发生的事情的假设:

    localStorage.setItem('mykey', null)
    console.log(localStorage.getItem('mykey')) // returns "null"
    

    因此,将mykey 显式设置为 null 实际上会将其设置为 "null" 字符串。

    为了让这种比较有效,你可以做

    if (localStorage.getItem('mykey') === 'null') {
      console.log('It is null');
    }
    

    【讨论】:

      【解决方案4】:

      检查localStorage是否为null。如果localStorage为null,则控件不会进入if块。

      【讨论】:

        【解决方案5】:

        如果你设置了localStorage.setItem('someKey', null),然后你会尝试获取并检查someKey这样的值localStorage.getItem('someKey') === null比较结果将false你需要在与null这样的@987654327比较之前使用JSON.parse()方法@

        【讨论】:

          猜你喜欢
          • 2017-03-19
          • 2021-04-02
          • 1970-01-01
          • 2017-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多