如何使用HTML中的本地存储在Array中存储数据

How to store data in Array using Local storage in HTML?

本文关键字:存储 Array 数据 何使用 HTML      更新时间:2023-09-26
    <!DOCTYPE html>
<html>
<body>
<input type="text" id="textstorage">
<button name="testbutton" onclick="myFunction()">send</button>
<div id="result"></div>
<script>
function myFunction(){
alert("dasd")
// Check browser support
var inp = document.getElementById("textstorage");
if (typeof(Storage) != "undefined") {
    // Store
    localStorage.setItem("result", inp.value);
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("result");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
document.getElementById("result").innerHTML = localStorage.getItem("result");

</script>
</body>
</html>

如何使用数组在网页中存储多个值。请帮帮我。

注意:如果我输入一个值,它将替换以前的值。我需要像数组一样存储所有值。

LocalStorage不支持数组,只支持字符串值。它存储key:value对。使用JSON.stringify()JSON.parse()将数组间接存储在LocalStorage对象中。

例如:

var arr = new Array();
arr[0] = "One";
arr[1] = "Two";
arr[2] = "Three";
localStorage["arr"] = JSON.stringify(arr);
var arrStored = JSON.parse(localStorage["arr"]);