关于前端:面试官居然要我用JS代码计算LocalStorage容量

6次阅读

共计 1557 个字符,预计需要花费 4 分钟才能阅读完成。

前言

大家好,我是林三心,用最通俗易懂的话讲最难的知识点 是我的座右铭,根底是进阶的前提 是我的初心

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`)
})()

能够得出残余可用容量

结语

我是林三心,一个热心的前端菜鸟程序员。如果你上进,喜爱前端,想学习前端,那咱们能够交朋友,一起摸鱼哈哈,摸鱼群,加我请备注【思否】

正文完
 0