Why is null stored as a string in localStorage?

删除回忆录丶 提交于 2020-01-21 08:30:45

问题


In the Chrome console I set foo to null:

localStorage.setItem("foo",null)

Then I test, whether it is null:

console.log(localStorage.getItem("foo")==null)

prints false.

Then I test, whether it is the string "null":

console.log(localStorage.getItem("foo")=="null")

prints true.

I thought that null was a legitimate Javascript value. Storing it as the string "null" is very counter intuitive and caused a strange bug in an otherwise working program, when I cleared the localStorage in the browser manually.


回答1:


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".




回答2:


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


来源:https://stackoverflow.com/questions/47150795/why-is-null-stored-as-a-string-in-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!