怎么使用JS代码计算LocalStorage容量

本篇内容主要讲解“怎么使用JS代码计算LocalStorage容量”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用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

怎么使用JS代码计算LocalStorage容量  js 第1张

已使用容量

计算已使用容量,我们只需要遍历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`)
})()

可以查看已用容量

怎么使用JS代码计算LocalStorage容量  js 第2张

剩余可用容量

我们已经计算出总容量和已使用容量,那么剩余可用容量 = 总容量 - 已使用容量

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 第3张

到此,相信大家对“怎么使用JS代码计算LocalStorage容量”有了更深的了解,不妨来实际操作一番吧!这里是蜗牛博客网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接