Javascript 为什么 localStorage["..."] 未定义,但 localStorage.getItem("...") 为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29519452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is localStorage["..."] undefined, but localStorage.getItem("...") is null?
提问by jaySon
Last time I checked, the following two lines returned true:
上次我检查时,返回了以下两行true:
null == localStorage["foo"];
null == localStorage.getItem("foo");
Same applies when replacing nullwith undefined.
So the first question is, why are there two ways to address the localStorage? And why does
替换null为时同样适用undefined。那么第一个问题是,为什么有两种方式来寻址localStorage?为什么
localStorage["foo"]
return undefinedwhile
返回undefined时
localStorage.getItem("foo")
returns null?
返回null?
Do I need to take care of that when developing JS?
在开发 JS 时我需要照顾它吗?
采纳答案by Alnitak
The Web Storage Specification requiresthat .getItem()returns nullfor an unknown key.
在Web存储规范要求是.getItem()返回null一个未知的关键。
Note however that .getItem()and .setItem()are specifically defined in the IDL as being the designated getterand setterfor the Storageinterface, and therefore they're also fully supported ways of accessing the contents of the storage.
但是请注意,.getItem()和.setItem()在 IDL 中专门定义为指定的getter和setter用于Storage接口,因此它们也完全支持访问存储内容的方式。
However the []syntax is more akin to a normal object and/or array property getter, and like those returns undefinedfor an unknown property name.
然而,[]语法更类似于普通对象和/或数组属性 getter,就像那些返回undefined未知属性名称的一样。
The reason notto 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 localStorageobject, c.f:
不使用[]语法的原因是它首先对对象属性进行操作,并且很高兴允许您覆盖localStorage对象的真实属性和方法,参见:
> localStorage['getItem'] = function() { return 0 }
> localStorage.getItem('getItem')
0
回答by muchweb
localStorage["..."]is invalid usage of localstorage. You are trying to access methods of the localstorageobject, rather than accessing actual database.
localStorage["..."]是本地存储的无效使用。您正在尝试访问localstorage对象的方法,而不是访问实际的数据库。
You have to use
你必须使用
localStorage.getItem("...")
and
和
localStorage.setItem("...")
methods to access storage database.
访问存储数据库的方法。
回答by Kadmillos
In javascript you always get an undefinedvalue for keys that does not exist inside an object.
在 javascript 中,你总是得到undefined一个对象内不存在的键的值。
a = {}; //new object
alert(a["test"]); // you get 'undefined' because "test" keys is not found
In localStorage .getItemis a method who does check keys inside the localStorage object and returns nullif not found.
在 localStorage 中,.getItem有一个方法会检查 localStorage 对象内的键,null如果没有找到则返回。
Don't blame javascript, it's just the localStorage object behaviour
不要责怪 javascript,这只是 localStorage 对象的行为

