如何检查本地存储空值是否为空?例如......
localStorage.setItem('favoriteflavor','');
var taste = localStorage.getItem('favoriteflavor');
if(taste == null){
console.log('favoriteflavor is null');
}
else {
console.log('favoriteflavor is NOT null');
}
这是最有意义的,但我没有得到任何结果。我也试过这个..
if(localStorage['favoriteflavor'] == 'null'){
console.log('favoriteflavor is null');
}
答案 0 :(得分:4)
如果将favoriteflavor
设置为空字符串,那么您应该检查它是否为空字符串
localStorage.setItem('favoriteflavor','');
var taste = localStorage.getItem('favoriteflavor');
if(taste == ''){
console.log('favoriteflavor is empty');
}
else{
console.log('favoriteflavor is NOT empty');
}
或者,如果您要删除favoriteflavor
,那么您可以将其检查为空
localStorage.setItem('favoriteflavor','chocolate');
delete localStorage['favoriteflavor'];
// or use localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');
if(taste == null){
console.log('favoriteflavor is null');
}
else
{
console.log('favoriteflavor is NOT null');
}
答案 1 :(得分:0)
您将项目设置为''在此处:
localStorage.setItem('favoritefla','');
并测试输出是否为== null
if(localStorage['favoriteflavor'] == 'null'
当它等于'',因为你自己之前已经设置了这个值。
我相信您正在尝试了解浏览器是否具有localStorage
容量,您可以通过测试是否可以插入和删除此对象中的项目来执行此操作,如下所示:
var hasStorage = (function() {
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
}());
如果broswer具有localStorage容量,则上述函数将返回true。我希望它有所帮助,欢呼