javascript - localStorage.getItem ('item' ) 是否优于 localStorage.item 或 localStorage ['item' ]?

标签 javascript syntax local-storage

我最近问了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 中不可互换。 :)

编辑: 正如 Christoph 在 his answer 中指出的那样, 函数式接口(interface)是在等于 localStorage 预定义属性的键下可靠地存储和检索值的唯一方法。 (其中有六个:lengthkeysetItemgetItemremoveItemclear。)因此,例如,以下内容将始终有效:

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/

相关文章:

python - python中 'if or'的语法错误。不确定代码有什么问题

c# - FROM close 中的语法错误?

javascript - 将 localStorage 字符串设置为整数

javascript - HTML5 LocalStorage重新加载文档

javascript - 单击时在对象数组中追加新数据

javascript - 创建每个项目具有不同系列数的多系列条形图

javascript - 如何在CxJS中制作功能组件?

javascript - 为什么变量在方法中未定义,但在 Typescript 的构造函数中却没有定义

javascript - ZURB 应用程序基础 [$injector :modulerr] error when adding modules

MYSQL IF NOT EXISTS/WHERE NOT EXISTS 错误