HTML5 localStorage有用的函数// JavaScript,TypeScript [关闭]

问题描述 投票:15回答:1

如何: *

  • 检查是否支持localStorage
  • 检查localStorage是否有物品
  • 获得localStorage留下的空间
  • 获得localStorage的最大空间
  • 获取localStorage中的二手空间
  • 获得localStorage的备份
  • 将备份应用于localStorage
  • 在控制台中转储localStorage的所有信息

*检查下面的答案


常问问题:

  • [link]如何在localStorage存储物体
  • [link]如何在localStorage中存储数组
  • [link]如何在localStorage中保存图像
  • [link] localStorage教程(还包括存储事件和要记住的事项)

有关:

  • [link]有关Web存储的一般信息
  • 当页面会话结束时,存储的[link] sessionStorage数据将被清除
  • [link] indexedDB是用于客户端存储结构化数据的低级API
javascript html html5 typescript local-storage
1个回答
21
投票

我在JavaScript和TypeScript中使用localStorage的函数套件

  • isSupported
  • hasItem(key)
  • getSpaceLeft()
  • getMaximumSace()
  • getUsedSpace()
  • getItemUsedSpace()
  • getBackup()
  • applyBackup(backup, fClear, fOverwriteExisting)
  • consoleInfo(fShowMaximumSize)

完整代码为GazHubGist上的LocalStorage-Module:JavaScriptTypeScript 实例:在JSFiddle

检查是否支持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;
    }
})();

检查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;
}

获取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;
}

获取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;
}

获取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;
}

获取空间使用我的项目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;
    }
}

备份关联数组,只有qazxsw poi

获取localStorage的备份 - TypeScript-Version

TypeScript-Version

将备份应用于localStorage - /** * 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; }

TypeScript-Version

转储控制台中localStorage的所有信息 - /** * 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); } }

TypeScript-Version

笔记

  • 每个键和值使用的精确空间量等于其字符串长度
  • 我测试中允许的最大存储空间:~5MB 5000000边缘 5242880 Chrome 5242880 Firefox 5000000 IE
  • Firefox问题:不要使用/** * 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); } } 但是:for (var key in localStorage)for (var i = 0; i < localStorage.length; ++i) { var key = localStorage.key(i)循环它会给for..in成员函数作为localStorages

//示例 - key

http://jsfiddle.net/1rqtd7pg/1/
© www.soinside.com 2019 - 2024. All rights reserved.