Why is null stored as a string in localStorage?

前端 未结 2 1351
灰色年华
灰色年华 2021-01-14 07:54

In the Chrome console I set foo to null:

localStorage.setItem(\"foo\",null)

Then I test, whether it is null:

相关标签:
2条回答
  • 2021-01-14 08:12

    As per spec, localstorage uses Storage object interface

    interface Storage {
      readonly attribute unsigned long length;
      DOMString? key(unsigned long index);
      getter DOMString? getItem(DOMString key);
      setter void setItem(DOMString key, DOMString value); //notice this line
      deleter void removeItem(DOMString key);
      void clear();
    };
    

    setter method translates to setItem, accepts only DOMString

    As per documentation

    DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String.

    Passing null to a method or parameter accepting a DOMString typically stringifies to "null".

    0 讨论(0)
  • 2021-01-14 08:31

    Please see https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

    All values are stored as strings in local storage. You should stringify data before storing it and parse data after retrieving it:

    localStorage.setItem("foo", JSON.stringify(null));
    var value = JSON.parse(localStorage.getItem("foo"));
    console.log(value === null);
    
    0 讨论(0)
提交回复
热议问题