localStorage - clear() or removeItem()?

localStorage - clear() or removeItem()?

本文关键字:removeItem or localStorage clear      更新时间:2023-09-26

我应该使用clear()来删除localStorage中的所有内容,还是应该手动removeItem()我在该特定网站上设置的内容(这很容易跟踪)?

我问,因为我不想最终清除用户的localStorage,如果他们有其他值设置。我在localhost中进行测试,并注意到通过使用clear(),我之前在其他项目中设置的所有内容都被清除了。

编辑:我应该提到我知道localStorage是域锁定的。我正在运行一个遵循以下结构的网站:

public-html
(localStorage)
--project1
----files
--project2
----files
--project3
----files

每个文件使用自己单独的localStorage变量。如果我在project2中localstorage.clear(), project1和project3的设置也会丢失

localstorage键指向一个原点。因此,如果您的所有项目都在本地主机上运行,那么当您使用clear()时,您将擦除所有值,唯一安全的方法是单独删除。

在生产环境中,每个项目都应该有自己的域,clear应该是安全的。

所以这是一个知道当前原点上还有什么的问题。如果您控制当前原点上的所有内容,并且不介意清除所有内容,那么clear()是最佳选择,并且是为此目的而设计的。如果你的代码的其他部分使用本地存储或其他项目托管在相同的起源,那么你会想要更多的选择和使用removeItem()

clear()清除当前原点(https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript)上的所有内容。在example.com上使用clear()不会影响example2.com的localStorage。它正在清除计算机上所有项目的数据,因为您拥有的所有测试文件都位于同一来源(http://localhostfile:///C:')。因此,使用clear()

就可以了

Clear() Method

  1. 将清除本地存储中的所有内容
  2. 不接受任何参数

removeItem()方法

  1. 将只删除你作为参数引用的localStorage项。
  2. 要使removeItem工作,你必须传入一个参数。例如:

removeItem("list")将只删除这个"list"关键项目

//为了更好地理解下面的代码

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="clear-method">Clear Method</button>
    <button id="removeItem-method">RemoveItem Method</button>

    <script>
        const clearMethod = document.getElementById("clear-method");
        const removeItemMethod = document.getElementById("removeItem-method");
        // declaring arraay for localStorage
        const computer = [
    {
        Brand: "Asus",
        Model: "Unknown"
    }
];
const phone = [
    {
        Brand: "Realme",
        Model: "Unknown"
    }
]
// setting up items on localStorage
localStorage.setItem("computer", JSON.stringify(computer));
localStorage.setItem("phone", JSON.stringify(phone));
        clearMethod.addEventListener("click", ()=>{
        localStorage.clear();
        })
        removeItemMethod.addEventListener("click", ()=>{
            localStorage.removeItem("phone");
        })
    </script>
   
</body>
</html>