问题描述
如果我使用localStorage.removeItem("key");
删除项目localStorage.removeItem("key");
有什么方法可以检查清除是否成功?
像回调或承诺之类的东西?
现在我正在这样做:
if(localStorage.getItem("key"))
localStorage.removeItem("key");
else
console.log("Error");
这是正确的方式还是可以“更好”的方式完成?
1楼
该removeItem()
调用不返回任何类型(摘自摘录的故障1的迹象, ,与我的重点):
removeItem(key)
方法必须使具有给定键的键/值对从与对象关联的列表中删除(如果存在)。 如果不存在带有该键的项,则该方法将不执行任何操作。
因此,判断密钥是否为实际删除的唯一方法(与上面第二句话中的“不执行任何操作”相反)是首先对其进行检查。
您几乎应该确定对getItem()
返回值是否为null
显式检查getItem()
当然使用===
),但这不会改变您无法使用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()
不能仅仅因为在项目不存在的情况下不做任何事情而失败(请参见上面的插图)。
2楼
更加准确的检查如下所示,否则,如果key
的值为""
(空字符串),则它将失败
if (localStorage.getItem("key") !== null) {
localStorage.removeItem("key");
} else {
console.log("Error");
}
如果找不到密钥,则将返回null
3楼
我今天[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] */