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")
这可能是存储系统的一个错误?有什么解决方案可以检查实际为空而不是“空”吗?
根据这个答案:
在 HTML5 localStorage 中存储对象
localStorage 用于保存 String 键值对,only!
null 是一个空对象。
所以这不是一个错误,它实际上是预期的行为。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)