javascript - 不明白为什么这段代码有效
问题描述
如果用户的浏览器是 IE,并且 localStorage 尚不存在,则以下代码设置一个 localStorage,其有效期为 24 小时。
(function ieAlert() {
var lastclear = window.localStorage.getItem('myLocalStorage'),
time_now = (new Date()).getTime();
var isIE = document.documentMode
if (isIE && !lastclear) {
if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {
window.localStorage.clear()
window.localStorage.setItem('myLocalStorage', time_now)
}
}
})()
有用。但我不明白的是这部分:
if (isIE && !lastclear) {
if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {
window.localStorage.clear()
window.localStorage.setItem('myLocalStorage', time_now)
}
}
这里lastclear
是未定义的,那么计算是如何进行的呢?
解决方案
这里
lastclear
是未定义的,那么计算是如何进行的呢?
不,是null
。getItem
返回null
不存在的条目。在数字上下文中,null
强制为,0
所以number - null
是。number - 0
number
(而如果原作者以另一种方式访问它localStorage.myLocalStorage
,则该值确实会是undefined
,并且>
不会起作用,因为number - undefined
is NaN
,并且所有与NaN
结果的比较都是false
。)
如果我正在编写代码,我不会依赖其中的null
强制部分,尤其是因为它会绊倒代码的未来读者(因为它会绊倒你)。但这就是它起作用的原因。
推荐阅读
- reactjs - react-hook-form - 每次提交后为空输入字段
- wordpress - 在将 woocommerce 中的商品添加到购物车之前添加免责声明消息
- python - 迭代包含嵌套数组的 pandas 数据框列(重新制定的请求)
- css - 如何解决响应式布局宽度问题
- function - 调用firebase云功能时权限被拒绝
- python - matplotlip 图例基本数据框列
- sql - SQL- 带日期的数学
- java - 如果为 null,则访问 T[].length 以全局返回 0
- firebase - 为什么我的 Firebase 实时数据库没有在 Firebase 控制台上打开?
- php - 从数组值更新几行表