Javascript比较localStorage的2个检查

Ais*_*war 3 javascript comparison html5 local-storage

我在diveintohtml5网站上看到了这个.这是他们检查浏览器是否支持localstorage的方式.

return 'localStorage' in window && window['localStorage'] !== null;

这会和刚做的一样吗?

return window.localStorage != undefined

Šim*_*das 8

1

return 'localStorage' in window && window['localStorage'] !== null;
Run Code Online (Sandbox Code Playgroud)

如果window对象包含具有名称的属性localStorage并且该属性的值不是,则返回true null.


2

return window.localStorage != undefined
Run Code Online (Sandbox Code Playgroud)

如果window对象包含具有名称的属性且该属性localStorage的值不是undefinednull (我假设全局属性undefined保存该值undefined) ,则返回true

  • @Šime一个问题:`typeof null ==='object'`所以如果window.localStorage为null,你将报告为true. (2认同)

Hem*_*ock 5

无论如何都是相同的结果,因为如果你得到的话.如果是null,你会得到因为.window.localStorageundefinedfalsewindow.localStoragefalseundefined == null

但是,我更喜欢使用!!,因为它是转换为布尔值的最快方式,如果它是false,null,undefined,',NaN或0,localStorage有多大用处?

return !!window.localStorage;
Run Code Online (Sandbox Code Playgroud)

编辑 一个警告,它们不完全相同,因为如果你设置window.localStorageundefined第一个会报告它true