检查localStorage.removeItem()是否成功

时间:2015-07-16 07:40:56

标签: javascript local-storage

如果我使用localStorage.removeItem("key");删除某个项目,我有什么方法可以检查删除是否成功?像回调或承诺的东西?

现在我这样做:

if(localStorage.getItem("key"))
    localStorage.removeItem("key");
else
    console.log("Error");

这是正确的方法,还是可以“更好”的方式完成?

3 个答案:

答案 0 :(得分:4)

removeItem()调用不会返回任何排序的 1 失败的任何迹象(摘录自a recent editor's draft of the W3C web storage specification,我强调):

  

removeItem(key)方法必须使具有给定键的键/值对从与对象关联的列表中删除(如果存在)。 如果没有包含该密钥的项目,则该方法必须无效。

因此,判断密钥是否为实际删除的唯一方法(与上面第二句中的"什么都不做"操作相反)是首先检查它

您几乎肯定会使用getItem()对[{1}}(当然null)明确检查===返回值,但这不会改变您可以&#39的事实; t用removeItem()本身 1 检测失败。

当然,如果您担心使用这些代码段来编写代码,那么您就可以完全定义一个函数来为您完成繁重的工作,例如:

function removeExistingItem(key) {
    if (localStorage.getItem(key) === null)
        return false;
    localStorage.removeItem(key);
    return true;
}

然后用更简洁的方式调用它:

if (! removeExistingItem("key"))
    console.log("Error");

1 这是基于"失败"被定义为不存在的密钥(似乎是你在问题中使用的定义)。实际上,removeItem() 无法失败只是因为在项目不存在的情况下它不会做任何事情(参见上面的插图)。

答案 1 :(得分:1)

更准确的检查将如下所示,否则如果key的值为""(空字符串),那么它将失败

if (localStorage.getItem("key") !== null) {
    localStorage.removeItem("key");
} else {
    console.log("Error");
}
如果找不到密钥,

Storage.getItem()将返回null

答案 2 :(得分:0)

我今天[06-23-2019]遇到了同样的问题,并调整了@paxdiablo的答案,为解决方案添加了更多故障保护功能。我真的希望我的版本可以帮助其他人节省我经历的时间和头痛:

/* Conditional Function supplements localStorage.removeItem(...) to return a [Boolean] 'success' or 'failure' value. [BEGIN] */

if (typeof removeLocalStorageItem !== 'function')
    {
        function removeLocalStorageItem(key) 
            {
                if (typeof (Storage) !== 'undefined')
                    {
                        if (localStorage.getItem(key) === null)
                            {
                                return false;
                            };

                        localStorage.removeItem(key);

                        if (localStorage.getItem(key) === null)
                            {
                                return true;
                            }
                        else
                            {
                                return false;
                            };
                    }
                else
                    {
                        return false;
                    };
            };
    };

/* Conditional Function supplements localStorage.removeItem(...) to return a [Boolean] 'success' or 'failure' value. [END] */