gpt4 book ai didi

javascript - 检查 localStorage.removeItem() 是否成功

转载 作者:行者123 更新时间:2023-11-30 08:35:55 27 4
gpt4 key购买 nike

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

现在我是这样做的:

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

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

最佳答案

removeItem() 调用不会返回任何任何 类型的失败指示1(摘自 a recent editor's draft of the W3C web storage specification,我的重点):

The removeItem(key) method must cause the key/value pair with the given key to be removed from the list associated with the object, if it exists. If no item with that key exists, the method must do nothing.

因此,判断 key 是否被实际删除(与上面第二句中的“什么都不做”操作相反)的唯一方法是先检查它。

您几乎可以肯定地使用 getItem() 返回值针对 null 的显式检查(当然使用 ===)但是不会改变您无法通过 removeItem() 本身1 检测到故障的事实。

当然,如果您担心这些片段会干扰您的代码,您完全可以定义一个函数来为您完成繁重的工作,例如:

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

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

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

1 这是基于“失败”被定义为 key 不存在(这似乎是您在问题中使用的定义)。实际上,removeItem() 不能 失败仅仅是因为它在项目不存在的情况下什么都不做(见上文插图)。

关于javascript - 检查 localStorage.removeItem() 是否成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com