【问题标题】:checking for not null not working with localStorage [duplicate]检查 not null 不使用 localStorage [重复]
【发布时间】:2015-11-25 04:09:24
【问题描述】:
var test = null;
if(test !== null){
    console.log('should not be logged in the console');//it worked
}


localStorage.setItem('foo',null);
console.log(localStorage.getItem('foo'));//logs null
if(localStorage.getItem('foo') !== null){
    console.log('should not be logged');//din't work, it's getting logged in the console
}

似乎 localStorage 将值 null 存储为字符串“null”。所以,下面的代码对我来说很好。

if(localStorage.getItem('foo') !== 'null'){

我还通过将 localStorage 值设置为 null 以外的值来确保代码对我有用。

这实际上不是答案。因为我们也可以将 localStorage 值设置为字符串 'null'。不是吗?

我知道我可以像 if(!variable){ 一样检查,但这会检查空字符串 ("")、null、undefined、false 以及数字 0 和 NaN。

还有一种方法可以仅使用以下方式检查 null:

if(variable === null && typeof variable === "object")

这可能是存储系统的错误?是否有任何解决方案可以检查实际为 null 而不是“null”?

【问题讨论】:

  • localStorage.getItem('foo') 将 null 作为字符串返回。所以使用if(localStorage.getItem('foo') !== 'null'){
  • localStorage 中存储的所有内容都是字符串格式。
  • “这可能是存储系统的错误?” -- 不,Web 存储(会话/本地)基本上是键值对。 From this ref - 键是字符串。任何字符串(包括空字符串)都是有效的键。值也是类似的字符串。。如果您愿意,可以存储空字符串,但不要尝试存储 null。 Null 在这里有一个特殊的含义——key(n) 仅当 n 大于或等于对象中键/值对的数量时才返回 null。

标签: javascript html local-storage


【解决方案1】:

根据这个答案:
Storing Objects in HTML5 localStorage

localStorage 用于保存字符串键值对,

null 是一个空对象。

所以这不是错误,它实际上是预期的行为。

【讨论】:

    【解决方案2】:

    您只能将string 存储在本地存储中。

    因此,当您在 localStorage 中保存 null 值时,您实际上是在 localStorage 中存储了 "null"(string)。

    要检查localStorage 中的值是否为null,请使用==

    例子:

    localStorage.setItem('foo', null);
    console.log(localStorage.getItem('foo')); //logs null as string
    console.log(typeof localStorage.getItem('foo')); //logs string
    
    if (localStorage.getItem('foo') != null) {
    //                              ^^         // Don't use strict comparison operator here
        console.log('Should work now!');
    }
    

    【讨论】:

    • 但是在控制台中它显示 null 而不是 'null' 为什么?
    • @BhojendraNepal 即'null' 字符串,您可以使用typeof 验证这一点
    • 我很困惑,如果它存储为字符串 'null' 或对象 null 并且忘记检查 typeof。谢谢。
    猜你喜欢
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2021-09-01
    • 1970-01-01
    相关资源
    最近更新 更多