首页 > 解决方案 > 不明白为什么这段代码有效

问题描述

如果用户的浏览器是 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是未定义的,那么计算是如何进行的呢?

标签: javascriptlocal-storage

解决方案


这里lastclear是未定义的,那么计算是如何进行的呢?

不,是nullgetItem返回null不存在的条目。在数字上下文中,null强制为,0所以number - null是。number - 0number

(而如果原作者以另一种方式访问​​它localStorage.myLocalStorage,则该值确实会是undefined,并且>不会起作用,因为number - undefinedis NaN,并且所有与NaN结果的比较都是false。)

如果我正在编写代码,我不会依赖其中的null强制部分,尤其是因为它会绊倒代码的未来读者(因为它会绊倒你)。但这就是它起作用的原因。


推荐阅读