本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
JS代码计算LocalStorage容量示例详解
lizhuang236 · 197浏览 · 发布于2022-07-05 +关注

这篇文章主要为大家介绍了JS代码计算LocalStorage容量的示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

LocalStorage 容量

localStorage的容量大家都知道是5M,但是却很少人知道怎么去验证,而且某些场景需要计算localStorage的剩余容量时,就需要我们掌握计算容量的技能了~~

计算总容量

我们以10KB一个单位,也就是10240B1024B就是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`)
})()


可以得出剩余可用容量 

以上就是JS代码计算LocalStorage容量示例详解的详细内容


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1312浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 896浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 957浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 953浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1077浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
我目前在一家互联网公司,从事运营工作,地标是南方的深圳,希望可以认识更多的朋友。
分类专栏
小鸟云服务器
扫码进入手机网页