如果用户的浏览器是 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
是未定义的,那么如何计算呢?
最佳答案
Here the
lastclear
is undefined, how does the calculation works then?
不,它是null
。 getItem
为不存在的条目返回 null
。在数字上下文中,null
强制转换为 0
,因此 number - null
是 number - 0
是 编号
。
(而如果原作者以另一种方式访问它,localStorage.myLocalStorage
,该值确实是undefined
,并且>
将不起作用,因为 number - undefined
是 NaN
,并且所有与 NaN
的比较都会导致 false
。 )
如果我正在编写代码,我不会依赖其中的 null
强制转换部分,尤其是因为它会绊倒代码的 future 读者(就像它绊倒你一样)。但这就是它起作用的原因。
关于javascript - 不明白为什么这段代码有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56974090/