gpt4 book ai didi

javascript - localStorage.getItem ('item' ) 比 localStorage.item 或 localStorage ['item' ] 更好吗?

转载 作者:行者123 更新时间:2023-11-28 07:40:29 25 4
gpt4 key购买 nike

我最近问过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.foolocalStorage['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; 将导致 aundefined,而 var a = localStorage.getItem('foo'); 将导致 a 的值为 null。正如您所发现的,undefinednull 在 JavaScript 中不可互换。 :)

编辑:正如克里斯托夫在 his answer 中指出的那样,函数接口(interface)是在等于 localStorage 的预定义属性的键下可靠地存储和检索值的唯一方法。 (其中有六个:lengthkeysetItemgetItemremoveItem > 和 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/28086435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com