【发布时间】: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