为什么localStorage [" ..."]未定义,但localStorage.getItem(" ...")为空? [英] Why is localStorage["..."] undefined, but localStorage.getItem("...") is null?

查看:82
本文介绍了为什么localStorage [" ..."]未定义,但localStorage.getItem(" ...")为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上次检查时,以下两行返回 true

Last time I checked, the following two lines returned true:

null == localStorage["foo"];
null == localStorage.getItem("foo");

null 替换为<$时同样适用C $ C>未定义。
所以第一个问题是,为什么有两种方法可以解决localStorage问题?为什么

Same applies when replacing null with undefined. So the first question is, why are there two ways to address the localStorage? And why does

localStorage["foo"]

返回未定义

localStorage.getItem("foo")

返回 null

开发JS时我需要注意吗?

Do I need to take care of that when developing JS?

推荐答案

网络存储规范要求 .getItem()返回 null 表示未知密钥。

The Web Storage Specification requires that .getItem() returns null for an unknown key.

但请注意, .getItem() .setItem()在IDL中被明确定义为指定的 getter setter 用于存储界面,因此他们'还完全支持访问存储内容的方式。

Note however that .getItem() and .setItem() are specifically defined in the IDL as being the designated getter and setter for the Storage interface, and therefore they're also fully supported ways of accessing the contents of the storage.

然而 [] 语法更类似于普通对象和/或数组属性getter,就像那些返回 undefined 的未知属性名一样。

However the [] syntax is more akin to a normal object and/or array property getter, and like those returns undefined for an unknown property name.

原因不是使用 [] 语法是它将首先对对象属性进行操作,并且非常乐意允许您覆盖 localStorage <的实际属性和方法/ code> object,cf:

The reason not to 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 localStorage object, c.f:

> localStorage['getItem'] = function() { return 0 }
> localStorage.getItem('getItem')
0

这篇关于为什么localStorage [&quot; ...&quot;]未定义,但localStorage.getItem(&quot; ...&quot;)为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆