簡體   English   中英

不明白為什么這段代碼有效

[英]Don't understand why this code is working

如果用戶的瀏覽器是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 - nullnumber - 0number

(如果原作者以另一種方式訪問​​了localStorage.myLocalStorage ,那么該值確實是undefined ,並且>將無效,因為number - undefinedNaN ,並且所有與NaN比較都會導致false 。)

如果我正在編寫代碼,我不會依賴它的那個null強制部分,尤其是因為它會絆倒未來的代碼讀者(因為它絆倒了你)。 但這就是它起作用的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM