HTML5 localStorage 有用的函数 // JavaScript、TypeScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34245593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 localStorage useful Functions // JavaScript, TypeScript
提问by CoderPi
How to: *
如何: *
- Check if
localStorage
is supported - Check if
localStorage
has an Item - Get the amount of space left in
localStorage
- Get the maximum amount of space in
localStorage
- Get the used space in
localStorage
- Get a Backup of
localStorage
- Apply a Backup to
localStorage
- Dump all information of
localStorage
in the console
- 检查是否
localStorage
支持 - 检查是否
localStorage
有项目 - 获取剩余的空间量
localStorage
- 获得最大的空间量
localStorage
- 获取已用空间
localStorage
- 获取备份
localStorage
- 将备份应用到
localStorage
- 转储
localStorage
控制台中的所有信息
*check the answers below
*检查下面的答案
FAQ:
常问问题:
- [link]How to store Objects in
localStorage
- [link]How to store an Array in
localStorage
- [link]How to save an Image in
localStorage
- [link]
localStorage
Tutorial (also covers storage eventsand things to remember)
- [链接]如何将对象存储在
localStorage
- [链接]如何将数组存储在
localStorage
- [链接]如何将图像保存在
localStorage
- [链接]
localStorage
教程(还包括存储事件和要记住的事情)
Related:
有关的:
回答by CoderPi
My suite of functions for localStorage
in JavaScript and TypeScript
我的localStorage
JavaScript 和 TypeScript函数套件
isSupported
hasItem(key)
getSpaceLeft()
getMaximumSace()
getUsedSpace()
getItemUsedSpace()
getBackup()
applyBackup(backup, fClear, fOverwriteExisting)
consoleInfo(fShowMaximumSize)
isSupported
hasItem(key)
getSpaceLeft()
getMaximumSace()
getUsedSpace()
getItemUsedSpace()
getBackup()
applyBackup(backup, fClear, fOverwriteExisting)
consoleInfo(fShowMaximumSize)
The complete code as LocalStorage
-Module on GitHubGist: JavaScriptand TypeScript
Live example: on JSFiddle
LocalStorage
GitHubGist 上的 -Module
完整代码:JavaScript和TypeScript
现场示例:JSFiddle
Check if localStorage is supported - TypeScript-Version
检查是否支持 localStorage - TypeScript-Version
/**
* Flag set true if the Browser supports localStorage, without affecting it
*/
var localStorage_isSupported = (function () {
try {
var itemBackup = localStorage.getItem("");
localStorage.removeItem("");
localStorage.setItem("", itemBackup);
if (itemBackup === null)
localStorage.removeItem("");
else
localStorage.setItem("", itemBackup);
return true;
}
catch (e) {
return false;
}
})();
Check if localStorage has an Item - TypeScript-Version
检查 localStorage 是否有一个项目 - TypeScript-Version
/**
* Check if localStorage has an Item / exists with the give key
* @param key the key of the Item
*/
function localStorage_hasItem(key) {
return localStorage.getItem(key) !== null;
}
Get the amount of space left in localStorage - TypeScript-Version
获取 localStorage 中剩余的空间量 - TypeScript-Version
/**
* This will return the left space in localStorage without affecting it's content
* Might be slow !!!
*/
function localStorage_getRemainingSpace() {
var itemBackup = localStorage.getItem("");
var increase = true;
var data = "1";
var totalData = "";
var trytotalData = "";
while (true) {
try {
trytotalData = totalData + data;
localStorage.setItem("", trytotalData);
totalData = trytotalData;
if (increase)
data += data;
}
catch (e) {
if (data.length < 2) {
break;
}
increase = false;
data = data.substr(data.length / 2);
}
}
if (itemBackup === null)
localStorage.removeItem("");
else
localStorage.setItem("", itemBackup);
return totalData.length;
}
Get the maximum amount of space in localStorage - TypeScript-Version
获取 localStorage 中的最大空间量 - TypeScript-Version
/**
* This function returns the maximum size of localStorage without affecting it's content
* Might be slow !!!
*/
function localStorage_getMaximumSize() {
var backup = localStorage_getBackup();
localStorage.clear()
var max = localStorage_getRemainingSpace();
localStorage_applyBackup(backup);
return max;
}
Get the used space in localStorage - TypeScript-Version
获取 localStorage 中的已用空间 - TypeScript-Version
/**
* This will return the currently used size of localStorage
*/
function localStorage_getUsedSize() {
var sum = 0;
for (var i = 0; i < localStorage.length; ++i) {
var key = localStorage.key(i)
var value = localStorage.getItem(key);
sum += key.length + value.length;
}
return sum;
}
Get the space used my an Item TypeScript-Version
获取我的项目TypeScript-Version使用的空间
/**
* This will return the currently used size of a given Item,returns NaN if key is not found
* @param key
*/
function getItemUsedSpace(key) {
var value = localStorage.getItem(key);
if (value === null) {
return NaN;
}
else {
return key.length + value.length;
}
}
Backup Assosiative Array, only TypeScript-Version
备份关联数组,仅TypeScript 版本
Get a Backup of localStorage - TypeScript-Version
获取 localStorage 的备份 - TypeScript-Version
/**
* This will return a localStorage-backup (Associative-Array key->value)
*/
function localStorage_getBackup() {
var backup = {};
for (var i = 0; i < localStorage.length; ++i) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
backup[key] = value;
}
return backup;
}
Apply a Backup to localStorage - TypeScript-Version
将备份应用到 localStorage - TypeScript-Version
/**
* This will apply a localStorage-Backup (Associative-Array key->value)
* @param backup associative-array
* @param fClear optional flag to clear all existing storage first.Default:true
* @param fOverwriteExisting optional flag to replace existing keys. Default: true
*/
function localStorage_applyBackup(backup, fClear, fOverwriteExisting) {
if (fClear === void 0) { fClear = true; }
if (fOverwriteExisting === void 0) { fOverwriteExisting = true; }
if (fClear == true) {
localStorage.clear();
}
for (var key in backup) {
if (fOverwriteExisting === false && backup[key] !== undefined) {
continue;
}
var value = backup[key];
localStorage.setItem(key, value);
}
}
Dump all information of localStorage in the console - TypeScript-Version
在控制台转储 localStorage 的所有信息 - TypeScript-Version
/**
* This functions dumps all keys and values of the local Storage to the console,
* as well as the current size and number of items
* @param fShowMaximumSize optional, flag show maximum size of localStorage. Default: false
*/
function localStorage_consoleInfo(fShowMaximumSize) {
if (fShowMaximumSize === void 0) { fShowMaximumSize = false; }
var amount = 0;
var size = 0;
for (var i = 0; i < localStorage.length; ++i) {
var key = localStorage.key(i)
var value = localStorage.getItem(key);
console.log(amount, key, value);
size += key.length + value.length;
amount++;
}
console.log("Total entries:", amount);
console.log("Total size:", size);
if (fShowMaximumSize === true) {
var maxSize = localStorage_getMaximumSize();
console.log("Total size:", maxSize);
}
}
Notes
笔记
- Each key and value is using the exact amount of space equal to its string length
- The maximum storage-space allowed in my tests: ~5MB
- 5000000 Edge
- 5242880 Chrome
- 5242880 Firefox
- 5000000 IE
- Firefox issue:Don't use
for (var key in localStorage)
but:for (var i = 0; i < localStorage.length; ++i) { var key = localStorage.key(i)
. Thefor..in
-loop it would give thelocalStorage
Memberfunctions askey
s
- 每个键和值都使用与其字符串长度相等的确切空间量
- 我的测试中允许的最大存储空间:~5MB
- 5000000 边缘
- 5242880 铬
- 5242880 火狐
- 5000000 IE
- Firefox 问题:不要使用
for (var key in localStorage)
但是:for (var i = 0; i < localStorage.length; ++i) { var key = localStorage.key(i)
。该for..in
-loop它会给localStorage
Memberfunctions为key
小号
// Example - http://jsfiddle.net/1rqtd7pg/1/
// 示例 - http://jsfiddle.net/1rqtd7pg/1/
console.log("LocalStorage supported:", LocalStorage.isSupported)
// true - I hope so anyways
if(LocalStorage.isSupported) {
localStorage.setItem("asd", "ASDASD")
// sets / overwrites the item "asd"
localStorage.setItem("asd" + Math.random(), "ASDASD")
// set another item each time you refresh the page
var backup = LocalStorage.getBackup()
// creates a backup, we will need it later!
console.log(JSON.stringify(backup))
// this is how the backup looks like
var usedSpace = LocalStorage.getUsedSpace()
// amount of space used right now
console.log("Used Space:", usedSpace)
var maxSpace = LocalStorage.getMaximumSpace()
// amount of maximum space aviable
console.log("Maximum Space:", maxSpace)
var remSpace = LocalStorage.getRemainingSpace()
// amount of remaining space
console.log("Remaining Space:", remSpace)
console.log("SpaceCheck", maxSpace === usedSpace + remSpace)
// true
console.log("hasItem", LocalStorage.hasItem("nothis0ne"))
// we don't have this one in our localStorage
localStorage.clear()
// oops, we deleted the localStorage!
console.log("has asd", LocalStorage.hasItem("asd"))
// item asd is lost
LocalStorage.applyBackup(backup)
// but we have a backup, restore it!
LocalStorage.consoleInfo()
// show all the info we have, see the backup worked
}