目录本地存储容量 计算总容量 已用容量 剩余可用容量
本地存储容量
大家都知道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上的存储属性,计算每个属性的长度,加起来就是已用容量~ ~ ~
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容量的更多信息,请关注编程网其他相关文章!