主要的思想:获取所有子项长度,进行叠加得出缓存使用的大小
function getStorageSize(storage){
if(typeof storage !== 'object' || storage === null){
throw new Error('计算的缓存不合法');
}else{
var size = 0;
for(item in storage) {
if(storage.hasOwnProperty(item)) {
size += storage.getItem(item).length;
}
}
return Number((size / 1024).toFixed(2));
}
}
var localSize = getStorageSize(window.localStorage);
console.log('localStorage当前大小', localSize, 'kb');
var sessionSize =getStorageSize(window.sessionStorage);
console.log('sessionStorage当前大小', sessionSize, 'kb');