我最近问了a question about LocalStorage .使用 JSON.parse(localStorage.item)
和 JSON.parse(localStorage['item'])
时无法返回 NULL
该项目尚未设置。
但是,JSON.parse(localStorage.getItem('item')
确实有效。结果是,JSON.parse(localStorage.testObject || null)
也有效。
One of the comments基本上说 localStorage.getItem()
和 localStorage.setItem()
应该始终是首选:
The getter and setter provide a consistent, standardised and crossbrowser compatible way to work with the LS api and should always be preferred over the other ways. -Christoph
我开始喜欢使用 localStorage 的简写点和括号符号,但我很想知道其他人对此的看法。 localStorage.getItem('item') 是否比 localStorage.item 或 localStorage['item'] 更好,或者只要它们有效,速记符号就可以吗?
最佳答案
直接属性访问(localStorage.foo
或 localStorage['foo']
)和使用功能接口(interface)(localStorage.getItem('foo')
) 工作正常。两者都是标准的并且跨浏览器兼容。* 根据 the spec :
The supported property names on a Storage object are the keys of each key/value pair currently present in the list associated with the object, in the order that the keys were last added to the storage area.
当找不到具有请求名称的键/值对时,它们的行为会有所不同。例如,如果键 'foo'
不存在,var a = localStorage.foo;
将导致 a
为 undefined
,而 var a = localStorage.getItem('foo');
将导致 a
具有值 null
。正如您所发现的,undefined
和 null
在 JavaScript 中不可互换。 :)
编辑: 正如 Christoph 在 his answer 中指出的那样, 函数式接口(interface)是在等于 localStorage
预定义属性的键下可靠地存储和检索值的唯一方法。 (其中有六个:length
、key
、setItem
、getItem
、removeItem
和 clear
。)因此,例如,以下内容将始终有效:
localStorage.setItem('length', 2);
console.log(localStorage.getItem('length'));
请特别注意,第一条语句不会影响属性 localStorage.length
(如果 中没有键
)。在这方面,规范似乎内部不一致。'length'
则可能会增加它本地存储
但是,以下可能不会执行您想要的操作:
localStorage.length = 2;
console.log(localStorage.length);
有趣的是,第一个在 Chrome 中是空操作,但在 Firefox 中是函数调用的同义词。第二个将始终记录 localStorage
中存在的 key 数。
* 这对于首先支持网络存储的浏览器来说是正确的。 (这包括几乎所有现代桌面和移动浏览器。)对于使用 cookie 或其他技术模拟本地存储的环境,行为取决于所使用的垫片。可以找到多个用于 localStorage
的 polyfill here .
关于javascript - localStorage.getItem ('item' ) 是否优于 localStorage.item 或 localStorage ['item' ]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148528/