Created
January 19, 2021 06:42
-
-
Save crazcdll/8762dd0aa95ea9a607acbb2d42ba028e to your computer and use it in GitHub Desktop.
计算 localStorage 所占空间
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 第一种计算方法 | |
| var _lsTotal = 0, // 总长度 | |
| _xLen, // 每一项的长度 | |
| _x; // 每一项的名称 | |
| var _ls = [] // 用来存储每一项 localStorage | |
| for (_x in localStorage) { | |
| if (!localStorage.hasOwnProperty(_x)) { | |
| continue; | |
| } | |
| _xLen = ((localStorage[_x].length + _x.length) * 2); // 每一项的长度包括 名字的长度+内容的长度,这里都按照一个字符占2个字节(2B)来简化计算 | |
| _lsTotal += _xLen; | |
| _ls.push({ | |
| name: _x, | |
| length: (_xLen / 1024).toFixed(4) | |
| }) | |
| } | |
| console.log('Total = ' + (_lsTotal / 1024).toFixed(4) + ' KB'); | |
| _ls = _ls.sort((a, b) => b.length - a.length) // 按照长度 从大到小 排序 | |
| _ls.forEach(item => console.log(item.name + ' : ' + (item.length / 1024).toFixed(4) + ' KB')) | |
| // 第二种计算方法 | |
| var localStorageSpace = function () { | |
| var allStrings = ''; | |
| for (var key in window.localStorage) { | |
| if (window.localStorage.hasOwnProperty(key)) { | |
| allStrings += window.localStorage[key]; | |
| } | |
| } | |
| return allStrings ? 3 + ((allStrings.length * 16) / (8 * 1024)) + ' KB' : 'Empty (0 KB)'; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment