[英]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 - null
是number - 0
是number
。
(如果原作者以另一種方式訪問了localStorage.myLocalStorage
,那么該值確實是undefined
,並且>
將無效,因為number - undefined
是NaN
,並且所有與NaN
比較都會導致false
。)
如果我正在編寫代碼,我不會依賴它的那個null
強制部分,尤其是因為它會絆倒未來的代碼讀者(因為它絆倒了你)。 但這就是它起作用的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.