Why is localStorage[“…”] undefined, but localStorage.getItem(“…”) is null?

五迷三道 提交于 2019-12-21 09:16:21

问题


Last time I checked, the following two lines returned true:

null == localStorage["foo"];
null == localStorage.getItem("foo");

Same applies when replacing null with undefined. So the first question is, why are there two ways to address the localStorage? And why does

localStorage["foo"]

return undefined while

localStorage.getItem("foo")

returns null?

Do I need to take care of that when developing JS?


回答1:


The Web Storage Specification requires that .getItem() returns null for an unknown key.

Note however that .getItem() and .setItem() are specifically defined in the IDL as being the designated getter and setter for the Storage interface, and therefore they're also fully supported ways of accessing the contents of the storage.

However the [] syntax is more akin to a normal object and/or array property getter, and like those returns undefined for an unknown property name.

The reason not to use [] syntax is that it will operate on object properties first and will quite happily allow you to overwrite real properties and methods of the localStorage object, c.f:

> localStorage['getItem'] = function() { return 0 }
> localStorage.getItem('getItem')
0



回答2:


localStorage["..."] is invalid usage of localstorage. You are trying to access methods of the localstorage object, rather than accessing actual database.

You have to use

localStorage.getItem("...")

and

localStorage.setItem("...")

methods to access storage database.




回答3:


In javascript you always get an undefined value for keys that does not exist inside an object.

a = {}; //new object
alert(a["test"]); // you get 'undefined' because "test" keys is not found

In localStorage .getItem is a method who does check keys inside the localStorage object and returns null if not found.

Don't blame javascript, it's just the localStorage object behaviour



来源:https://stackoverflow.com/questions/29519452/why-is-localstorage-undefined-but-localstorage-getitem-is-null

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