面试官居然要我用JS代码计算LocalStorage容量!
作者:Sunshine_Lin
来源:SegmentFault 思否社区
前言
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`)
})()

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



关注公众号:拾黑(shiheibook)了解更多
赞助链接:
关注数据与安全,洞悉企业级服务市场:https://www.ijiandao.com/
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
- 加币兑换人民币汇率2024年2月27日
- 宝马X1、极氪X、ID.7,2023上海车展新车看点一目了然
- 光纤是“空心”的,但微软却很“实在”
- 中国电子信息产业发展研究院发布《中国新型显示产业发展现状与趋势洞察》报告
- TypeScript 遭库开发者嫌弃;苹果秋季发布会时间确定;PyCharm 2022.2.1 发布| 思否周刊
- 美国调整科技遏华策略值得关注
- 欢庆祖国生日
- 百万奖金,五大赛道!统信邀您参加解决方案大赛
- 比特熊“新家”装修完毕,欢迎你成为首批访客
- 电信运营商的“提速降费”发展思考
- 联想前副总裁赵泓担任柔宇科技COO;美国解除对小米“中国军方公司”的认定;特斯拉已在中国建立数据中心 | Do早报
- 【杂谈快报】曝华为正研发3nm芯片:麒麟9010正在设计
赞助链接