如果localStorage键值不存在 [英] if localStorage key value doesn't exist
本文介绍了如果localStorage键值不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果没有localStorage键值,我正在尝试隐藏div.
I am trying to hide my div if there is no a localStorage key value.
在下面的代码行中,我仅实现了在localStorage键完全删除时隐藏div,但是如果localStorage 键根本没有任何价值,则需要执行同样的操作.
With the line below I achieved only to hide a div when localStorage key completely deleted but need to do the same if localStorage key hasn't got any value at all just [].
window.localStorage.getItem('items') === null
它将如何执行?
推荐答案
您可以使用OR
运算符||
var items = window.localStorage.getItem('items')
if (items === null || items.length === 0)
{
// items is null, [] or '' (empty string)
}
如果您还必须在某处检查undefined
,则可以将=== null
更改为== null
或使用类似这样的额外条件进行扩展
If you have to check for undefined
somewhere as well you can change === null
to == null
or expand with an extra condition like this
if (items === undefined || items === null || items.length === 0)
{
// items is undefined, null, [] or '' (empty string)
}
编辑:这是您可以直接获取数组的方法
Here is what you can do to get the array directly
var items = JSON.parse(window.localStorage.getItem('items'))
if (items === null || items.length === 0)
{
// items is null or []
}
这篇关于如果localStorage键值不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文