当前位置: 首页 > Web前端 > HTML

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

时间:2023-03-28 16:09:38 HTML

前言大家好。我是林三鑫。用最通俗易懂的语言讲述最难的知识点是我的座右铭。基础是进阶的前提。很少有人知道如何验证,而在某些场景下我们需要计算localStorage的剩余容量时,我们需要掌握计算容量的技巧~~我们以10KB为单位计算总容量,即10240B,并且1024B是10240字节我们在localStorage中不断的积累10KB,当超过最大存储量的时候就会报错。到时候把所有累计的size都统计出来,就是总的存储容量!注意:计算前需要清空LocalStorageletstr='0123456789'lettemp=''//先做一个10KB的字符串while(str.length!==10240){str=str+'0123456789'}//先清空localStorage.clear()constcomputedTotal=()=>{returnnewPromise((resolve)=>{//继续在LocalStorage中累积10KBconsttimer=setInterval(()=>{try{localStorage.setItem('temp',temp)}catch{//错误提示超出最大存储resolve(temp.length/1024-10)clearInterval(timer)//计数后记得清除localStorage.clear()}temp+=str},0)})}(async()=>{consttotal=awaitcomputedTotal()console.log(`最大容量${total}KB`)})()最终最大存储容量为5120KB≈5M已使用容量calculated使用capacity,我们只需要遍历localStoragebody上的storageattribute,并计算每一个的长度,累加的capacity就是使用的capacity~~~constcomputedUse=()=>{letcache=0for(letkeyinlocalStorage){if(localStorage.hasOwnProperty(key)){cache+=localStorage.getItem(key).length}}return(cache/1024).toFixed(2)}(async()=>{consttotal=awaitcomputedTotal()leto='0123456789'对于(leti=0;i<1000;i++){o+='0123456789'}localStorage.setItem('o',o)constuseCache=computedUse()console.log(`used${useCache}KB`)})()可以查看已用容量和剩余可用容量我们计算了总容量和已用容量,那么剩余可用容量=总容量-已用容量constcomputedsurplus=(total,use)=>{returntotal-use}(async()=>{consttotal=awaitcomputedTotal()leto='0123456789'for(leti=0;i<1000;i++){o+='0123456789'}localStorage.setItem('o',o)constuseCache=computedUse()console.log(`remaining可用容量${computedsurplus(total,useCache)}KB`)})()可以得到剩余的可用容量成员。如果你有上进心,喜欢前端,想学前端,那我们可以交个朋友,一起钓鱼哈哈,摸摸鱼群,加我,请注意[思想]