上次我检查时,返回了以下两行true
:
null == localStorage["foo"];
null == localStorage.getItem("foo");
更换时同样适用null
with undefined
。
那么第一个问题是,为什么有两种方式来寻址localStorage?为什么会这样
localStorage["foo"]
return undefined
while
localStorage.getItem("foo")
returns null
?
开发JS的时候需要注意这个吗?
The 网络存储规范要求 http://dev.w3.org/html5/webstorage/#the-storage-interface that .getItem()
回报null
对于未知的密钥。
但请注意.getItem()
and .setItem()
在 IDL 中被明确定义为指定的getter
and setter
为了Storage
接口,因此它们也是完全支持的访问存储内容的方式。
但是,那[]
语法更类似于普通对象和/或数组属性 getter,并且像那些返回一样undefined
对于未知的属性名称。
原因not to use []
语法是,它将首先对对象属性进行操作,并且很高兴地允许您覆盖对象的真实属性和方法localStorage
对象,参见:
> localStorage['getItem'] = function() { return 0 }
> localStorage.getItem('getItem')
0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)