localStorage的容量大家都知道是5M,但是卻很少人知道怎么去驗證,而且某些場景需要計算localStorage的剩余容量時,就需要我們掌握計算容量的技能了~~
我們以10KB一個單位,也就是10240B,1024B就是10240個字節的大小,我們不斷往localStorage中累加存入10KB,等到超出最大存儲時,會報錯,那個時候統計出所有累積的大小,就是總存儲量了!
注意:計算前需要先清空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) // 統計完記得清空 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`)})()
可以查看已用容量
圖片
我們已經計算出總容量和已使用容量,那么剩余可用容量 = 總容量 - 已使用容量
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`)})()
可以得出剩余可用容量
本文鏈接:http://www.www897cc.com/showinfo-26-82034-0.html面試官居然要我用JS代碼計算LocalStorage容量!
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 分布式限流方案的探索與實踐