js计算字符串存储大小

let str = "dasadasdadasdasdsadasdasdasda";
function getSessionStorageSize(key) {
    const item = sessionStorage.getItem(key);
    let size = JSON.stringify(item).length * 2;
    const arr = [‘bytes‘, ‘KB‘, ‘MB‘, ‘GB‘, ‘TB‘];
    let sizeUnit = 0;

    while(size > 1024) {
        size /= 1024;
        ++sizeUnit;
    }

    return `${key}的大小为:${size.toFixed(2)}${arr[sizeUnit]}`;
}
sessionStorage.setItem("str",str);
console.log(getSessionStorageSize("str"));

js计算字符串存储大小

 

 

 

(function() {
    if(!window.localStorage) {
        console.log(‘当前浏览器不支持localStorage!‘)
    }    
    var test = ‘0123456789‘;
    var add = function(num) {
        num += num;
        if(num.length == 10240) {
            test = num;
            return;
        }
        add(num);
    }
    add(test);
    var sum = test;
    var show = setInterval(function(){
        sum += test;
        try {
            window.localStorage.removeItem(‘test‘);
            window.localStorage.setItem(‘test‘, sum);
            console.log(sum.length / 1024 + ‘KB‘);
        } catch(e) {
            alert(sum.length / 1024 + ‘KB超出最大限制‘);
            clearInterval(show);
        }
    }, 20)
})()

亲测Chrome浏览器中localStorage最大5120kb,即5M。

 

 

 

js计算字符串存储大小

上一篇:全新的 Vue3 状态管理工具:Pinia


下一篇:解决 flutter webrtc 有时候无法进行视频通话,但有时候又好使(前提:turn 和stun 已准备好)