Ais*_*war 3 javascript comparison html5 local-storage
我在diveintohtml5网站上看到了这个.这是他们检查浏览器是否支持localstorage的方式.
return 'localStorage' in window && window['localStorage'] !== null;
这会和刚做的一样吗?
return window.localStorage != undefined
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
的值不是undefined
或null
(我假设全局属性undefined
保存该值undefined
) ,则返回true
无论如何都是相同的结果,因为如果你得到的话.如果是null,你会得到因为.window.localStorage
undefined
false
window.localStorage
false
undefined == null
但是,我更喜欢使用!!
,因为它是转换为布尔值的最快方式,如果它是false,null,undefined,',NaN或0,localStorage有多大用处?
return !!window.localStorage;
Run Code Online (Sandbox Code Playgroud)
编辑
一个警告,它们不完全相同,因为如果你设置window.localStorage
为undefined
第一个会报告它true