当通过密钥访问本地存储时,Firefox和Chrome会返回不同的值。
alert(localStorage.mykey); // FF = null, Chrome = undefined
alert(localStorage.getItem('mykey')); // FF = null, Chrome = null
请参阅Firefox错误localStorage/sessionStorage should return undefined (not null) for undefined keys.
从本质上讲,Chrome和其他浏览器会像localStorage.mykey
那样将getItem()
视为任何其他数组对象。
所以,我的问题是:鉴于这种差异,检查localStorage中是否存在密钥的最佳方法是什么?
选项1:if(localStorage.getItem('key') === null)
选项2:if(localStorage.key === null || localStorage.key === undefined)
选项3:如何在#2中没有||
的情况下检查localStorage.key?
答案 0 :(得分:1)
您使用的是哪个版本的Firefox?在这种情况下,最新版本(我使用Firefox 14测试)返回undefined
。无论如何,简单的测试是typeof localStorage.key == "string"
。