How to set localstorage item back to null.

前端 未结 2 1795
醉话见心
醉话见心 2020-12-30 22:32

I\'m using a system to alert users when a major update has happened to a site, and I do it with LocalStorage, when I made the system, I made the system check if tip was \"nu

相关标签:
2条回答
  • 2020-12-30 23:03

    There is no way to set a localStorage item to have a value of null. Use remove instead.

    Any localStorage item either has a string value, or it does not exist. No other type is possible, therefore no variation of null is possible either.

    The confusing part is that as you noticed in your example, if you call localStorage.getItem('tip') and it does not exist, you’ll see a null return value in the debugger or when attempting to display the value.

    As unintuitive as this is, it doesn’t mean a local storage item actually exists with a value of null. It really means the item 'tip' does not exist at all. There is not even a single internal trace anywhere of anything related to the key ‘tip’.

    For an item that does exist, if you are trying to set the item "back to null" (which is impossible), what you should be doing instead is to remove the item.

    In your example, this will cause you see the return value displayed as null again, like when you first called localStorage.getItem('tip'), even though it’s not null, it just doesn’t exist at all. To do that you can remove the item as described below.

    Just remember all you ever need is get, set, and remove.

    localStorage.getItem('tip')                             // Get item value
    localStorage.setItem('tip','cool stuff')     // Set item value
    localStorage.removeItem('tip')                       // Remove item
    if (localStorage.getItem('tip') === null)  // Check if item exists

    Technically, @Michael Theriot‘s answer was suggesting to set the item tip to a string value of "null". That’s not much different that setting it to “dog”, in that neither one of them is actually a system recognized null value.

    I’m guessing that’s not what you meant, however even if it were, I would tend to advise against the practice because it can become confusing to others maintaining your code.

    0 讨论(0)
  • 2020-12-30 23:04

    localStorage.removeItem('tip') if you are aiming to remove the key

    localStorage.setItem('tip', 'null') if you just want to set it to the string "null"

    0 讨论(0)
提交回复
热议问题