JS代碼計算LocalStorage容量示例詳解
LocalStorage 容量
localStorage
的容量大家都知道是5M
,但是卻很少人知道怎么去驗證,而且某些場景需要計算localStorage
的剩余容量時,就需要我們掌握計算容量的技能了~~
計算總容量
我們以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`) })()
可以查看已用容量
剩余可用容量
我們已經計算出總容量和已使用容量,那么剩余可用容量 = 總容量 - 已使用容量
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`) })()
可以得出剩余可用容量
以上就是JS代碼計算LocalStorage容量示例詳解的詳細內容,更多關于JS計算LocalStorage容量的資料請關注腳本之家其它相關文章!
相關文章
Layui table 組件的使用之初始化加載數(shù)據、數(shù)據刷新表格、傳參數(shù)
這篇文章主要介紹了Layui table 組件的使用之初始化加載數(shù)據、數(shù)據刷新表格、傳參數(shù)的實現(xiàn)代碼,需要的朋友可以參考下2017-09-09WEB前端開發(fā)框架Bootstrap3 VS Foundation5
WEB前端開發(fā)框架Bootstrap3 VS Foundation5,這篇文章主要介紹了Bootstrap3與Foundation5的五大區(qū)別,感興趣的小伙伴們可以參考一下2016-05-05bootstrap自定義樣式之bootstrap實現(xiàn)側邊導航欄功能
bootstrap自帶的響應式導航欄是向下滑動的,有時滿足不了個性化的需求,需要做一個類似于android drawerLayout 側滑的菜單,這就是我要實現(xiàn)的bootstrap自定義側滑菜單。接下來通過本文給大家介紹bootstrap實現(xiàn)側邊導航欄功能,感興趣的朋友一起看看吧2018-09-09js的.innerHTML = ""IE9下顯示有錯誤的解決方法
js的.innerHTML= "……"在ie9- 的版本顯示不正常,使用jquery可以解決,有類似問題的朋友可以參考下2013-09-09