自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

面試官居然要我用JS代碼計算LocalStorage容量!

開發(fā) 前端
我們以10KB一個單位,也就是10240B,1024B就是10240個字節(jié)的大小,我們不斷往localStorage中累加存入10KB,等到超出最大存儲時,會報錯,那個時候統(tǒng)計出所有累積的大小,就是總存儲量了!

LocalStorage 容量

localStorage的容量大家都知道是5M,但是卻很少人知道怎么去驗證,而且某些場景需要計算localStorage的剩余容量時,就需要我們掌握計算容量的技能了~~

計算總?cè)萘?/h2>

我們以10KB一個單位,也就是10240B,1024B就是10240個字節(jié)的大小,我們不斷往localStorage中累加存入10KB,等到超出最大存儲時,會報錯,那個時候統(tǒng)計出所有累積的大小,就是總存儲量了!

注意:計算前需要先清空LocalStorage

let str = '0123456789'
let temp = ''
// 先做一個 10KB 的字符串
while (str.length !== 10240) {
  str = str + '0123456789'
}

// 先清空
localStorage.clear()

const computedTotal = () => {
  return new Promise((resolve) => {
    // 不斷往 LocalStorage 中累積存儲 10KB
    const timer = setInterval(() => {
      try {
        localStorage.setItem('temp', temp)
      } catch {
        // 報錯說明超出最大存儲
        resolve(temp.length / 1024 - 10)
        clearInterval(timer)
        // 統(tǒng)計完記得清空
        localStorage.clear()
      }
      temp += str
    }, 0)
  })
}

(async () => {
  const total = await computedTotal()
  console.log(`最大容量${total}KB`)
})()

最后得出的最大存儲量為5120KB ≈ 5M

圖片圖片

已使用容量

計算已使用容量,我們只需要遍歷localStorage身上的存儲屬性,并計算每一個的length,累加起來就是已使用的容量了~~~

const computedUse = () => {
  let cache = 0
  for(let key in localStorage) {
    if (localStorage.hasOwnProperty(key)) {
      cache += localStorage.getItem(key).length
    }
  }
  return (cache / 1024).toFixed(2)
}

(async () => {
  const total = await computedTotal()
  let o = '0123456789'
  for(let i = 0 ; i < 1000; i++) {
    o += '0123456789'
  }
  localStorage.setItem('o', o)
  const useCache = computedUse()
  console.log(`已用${useCache}KB`)
})()

可以查看已用容量

圖片圖片

剩余可用容量

我們已經(jīng)計算出總?cè)萘亢鸵咽褂萌萘浚敲词S嗫捎萌萘?= 總?cè)萘?- 已使用容量

const computedsurplus = (total, use) => {
  return total - use
}

(async () => {
  const total = await computedTotal()
  let o = '0123456789'
  for(let i = 0 ; i < 1000; i++) {
    o += '0123456789'
  }
  localStorage.setItem('o', o)
  const useCache = computedUse()
  console.log(`剩余可用容量${computedsurplus(total, useCache)}KB`)
})()

可以得出剩余可用容量

責任編輯:武曉燕 來源: 前端之神
相關推薦

2024-05-09 10:33:14

JS計算容量

2022-11-04 08:47:52

底層算法數(shù)據(jù)

2021-12-13 09:02:13

localStorag面試前端

2021-12-02 08:19:06

MVCC面試數(shù)據(jù)庫

2021-02-28 07:52:24

蠕蟲數(shù)據(jù)金絲雀

2020-09-08 06:43:53

B+樹面試索引

2024-08-05 01:26:54

2020-08-03 07:38:12

單例模式

2022-07-13 17:47:54

布局Flex代碼

2020-07-02 07:52:11

RedisHash映射

2022-08-08 13:45:12

Redis面試Hash

2020-02-25 16:56:02

面試官有話想說

2022-05-23 08:43:02

BigIntJavaScript內(nèi)置對象

2025-03-12 00:52:00

Java樂觀鎖悲觀鎖

2022-06-06 15:06:42

MySQLJAVA

2021-11-24 07:56:56

For i++ ++i

2021-03-24 10:25:24

優(yōu)化VUE性能

2009-09-28 10:58:45

招聘

2021-09-28 13:42:55

Chrome Devwebsocket網(wǎng)絡協(xié)議

2015-08-13 10:29:12

面試面試官
點贊
收藏

51CTO技術棧公眾號