面试官居然要我用JS代码计算LocalStorage容量!

开发 前端
我们以10KB一个单位,也就是10240B,1024B就是10240个字节的大小,我们不断往localStorage中累加存入10KB,等到超出最大存储时,会报错,那个时候统计出所有累积的大小,就是总存储量了!

LocalStorage 容量

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身上的存储属性,并计算每一个的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`)
})()

可以得出剩余可用容量

责任编辑:武晓燕 来源: 前端之神
相关推荐

2022-11-04 08:47:52

底层算法数据

2021-12-13 09:02:13

localStorag面试前端

2021-12-02 08:19:06

MVCC面试数据库

2021-02-28 07:52:24

蠕虫数据金丝雀

2020-09-08 06:43:53

B+树面试索引

2020-08-03 07:38:12

单例模式

2020-07-02 07:52:11

RedisHash映射

2022-08-08 13:45:12

Redis面试Hash

2022-07-13 17:47:54

布局Flex代码

2020-02-25 16:56:02

面试官有话想说

2022-06-06 15:06:42

MySQLJAVA

2022-05-23 08:43:02

BigIntJavaScript内置对象

2021-11-24 07:56:56

For i++ ++i

2015-08-13 10:29:12

面试面试官

2020-05-22 08:11:48

线程池JVM面试

2021-05-28 11:18:50

MySQLbin logredo log

2020-12-10 08:43:17

垃圾回收JVM

2021-03-24 10:25:24

优化VUE性能

2021-09-28 13:42:55

Chrome Devwebsocket网络协议

2009-09-28 10:58:45

招聘
点赞
收藏

51CTO技术栈公众号