if localStorage key value doesn't exist

2019-07-17 04:27发布

I am trying to hide my div if there is no a localStorage key value.

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

How would it be performed?

3条回答
看我几分像从前
2楼-- · 2019-07-17 04:55
Storage.prototype.has = function(key) {
  return (key in this && !(key in Storage.prototype));
};
查看更多
Juvenile、少年°
3楼-- · 2019-07-17 04:59

How about simply:

if (!localStorage.nameOfYourLocalStorage) {
    // do the following if the localStorage.nameOfYourLocalStorage does not exist
}

An example of how it could be useful:

if (!localStorage.nameOfYourLocalStorage) {
    localStorage.nameOfYourLocalStorage = defaultValue;
}

Here the script will check if the localStorage name does not exist, and if it doesn't, it will create it with the default value.

And if you want it to act when it does exist, you can add an else after the if block to continue, or remove the '!' from the if block condition.

查看更多
霸刀☆藐视天下
4楼-- · 2019-07-17 05:05

You can add required conditions using the OR operator ||

var items = window.localStorage.getItem('items')

if (items === null || items.length === 0)
{
    // items is null, [] or '' (empty string)
}

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)
}

EDIT: 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 []
}
查看更多
登录 后发表回答