How can I check if a localstorage variable is null or undefined?

后端 未结 6 1506
难免孤独
难免孤独 2021-02-05 11:35

I have this code:

var sideBar = localStorage.getItem(\'Sidebar\');

I want to check if sideBar is defined and not null in an if statement. I am

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 12:15

    As W3 Manual explicitly explained: The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

    It means, no need to check undefined, If it is undefined then the result of the getItem() method will be null. You need to just check against null.

    if (localStorage.getItem("Sidebar") !== null) {
    //...
    }
    

提交回复
热议问题