gpt4 book ai didi

javascript - 检查 not null 不使用 localStorage

转载 作者:行者123 更新时间:2023-12-05 08:17:28 24 4
gpt4 key购买 nike

<分区>

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'?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com