面試官居然要我用JS代碼計(jì)算LocalStorage容量!
作者:Sunshine_Lin
來源:SegmentFault 思否社區(qū)
前言
LocalStorage 容量
計(jì)算總?cè)萘?/span>
let str = '0123456789'
let temp = ''
// 先做一個(gè) 10KB 的字符串
while (str.length !== 10240) {
str = str + '0123456789'
}
// 先清空
localStorage.clear()
const computedTotal = () => {
return new Promise((resolve) => {
// 不斷往 LocalStorage 中累積存儲(chǔ) 10KB
const timer = setInterval(() => {
try {
localStorage.setItem('temp', temp)
} catch {
// 報(bào)錯(cuò)說明超出最大存儲(chǔ)
resolve(temp.length / 1024 - 10)
clearInterval(timer)
// 統(tǒng)計(jì)完記得清空
localStorage.clear()
}
temp += str
}, 0)
})
}
(async () => {
const total = await computedTotal()
console.log(`最大容量${total}KB`)
})()

已使用容量
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`)
})()


評(píng)論
圖片
表情
