JavaScript 如何将数组存储在localStorage中
在本文中,我们将看看如何使用javascript将数组存储在localStorage中。
javascript的localStorage由浏览器提供,是一个非常轻量级的存储,可以将数据存储在键值对中。键必须是唯一的,值以UTF-16 DOM字符串格式存储。因此,我们不能直接将数组存储在localStorage中,因为它只允许存储字符串。
方法: 为了将数组存储在localStorage中,您可以按照以下步骤进行操作:
使用JSON.stringify()方法将数组转换为字符串。
let string = JSON.string(array)
将转换后的字符串存储在localStorage中。
localStorage.setItem("key", string)
现在,要检索数组,您可以从本地存储中访问字符串值,并使用 JSON.parse() 方法解析字符串并将其转换回数组。
// Retrieving the string
let retString = localStorage.getItem("key")
// Retrieved array
let retArray = JSON.parse(retString)
例子1: 我们有一个包含学生姓名的数组。我们使用上述方法将数组存储起来,然后解析并在控制台中显示。
存储数组:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to store an array in localStorage ?
</title>
</head>
<body>
<script>
let students = ["Vikas", "Utsav", "Pranjal",
"Aditya", "Arya"]
let string = JSON.stringify(students)
localStorage.setItem("students", string)
</script>
</body>
</html>
现在,要查看存储的字符串,打开检查部分中的“ 应用程序 ”选项卡,并进入“ 本地存储 ”。
检索数组: 要检索存储的数组,我们使用以下代码:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to store an array in localStorage?
</title>
</head>
<body>
<script>
let retString = localStorage.getItem("students")
let retArray = JSON.parse(retString)
console.log(retArray);
</script>
</body>
</html>
控制台输出:
例子2: 在这个例子中,我们将一个数组“ todos ”存储在localStorage中,然后稍后我们检索了这个数组,并使用一个for循环迭代整个数组,并将该数组显示在HTML代码中。
存储数组
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to store an array in localStorage?
</title>
</head>
<body>
<script>
let todos = [
"Go to gym",
"Studying for 2 hours",
"Chilling out with friends",
"Checking out GeeksforGeeks"
]
localStorage.setItem("todos", JSON.stringify(todos))
</script>
</body>
</html>
存储输出:
检索“todos”并显示在网页上
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to store an array in localStorage?
</title>
</head>
<body style="font-family: sans-serif;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>My todos are:</h3>
<ul class="todos"></ul>
<script>
let todos = JSON.parse(localStorage.getItem("todos"))
let todoList = document.querySelector(".todos")
todos.forEach(todo => {
let li = document.createElement("li")
li.innerText = todo
todoList.appendChild(li)
});
</script>
</body>
</html>
输出: