所以基本上我正在尝试创建从中存储一些用户信息在本地存储和更新和删除用户的信息我刚刚开始处理它但卡在本地存储中插入完整的用户数据。每当我将用户数据存储在本地存储中时(对象:对象)。
<!DOCTYPE html>
<html>
<body>
First Name: <input type="text" id="fname" placeholder="Enter First Name Here">
Id: <input type="text" id="id" placeholder="Enter id Here"><br><br>
<button onclick="myFunction()" >Submit</button>
<br>
<br>
<p id="demo"></p>
<div id="result"></div>
<script>
function myFunction(){
var fname = document.getElementById("fname").value;
var id = document.getElementById("id").value;
if (typeof(Storage) !== "undefined") {
// Store
var person = [ firstName: fname , ID : id ];
var tempitem =[ [localStorage.getItem("record")] ];
console.log();
tempitem.push(person);
localStorage.setItem("record", tempitem);
//Check if an item can be deleted using index number
}
else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>
</body>
</html>
对于在本地存储中存储数据是非常重要的,记住你只能存储字符串值。存储对象或数组(或对象数组)时,您必须先将数据转换为 JSON。
这很简单:
localStorage.setItem("record", JSON.stringify(data));
并再次读取值:
var record = JSON.parse(localStorage.getItem("record"));
如果您不这样做,Javascript 将尝试使用该toString()
方法对数据本身进行字符串化。对于对象,这意味着[object Object]
将存储值而不是对象的实际内容。
此外,您似乎混淆了 Javascript 对象和数组。
这是一个对象:
{
firstName: "John"
ID: "10"
}
这是一个数组:
[10, 20, 30, 40, 50]
请注意在定义对象时使用 '{' 和 '}' 以及在定义数组时使用 '[' 和 ']'。另请注意,我们可以在对象中拥有命名属性,而在数组中则无法拥有。
一个对象数组将如下所示:
[
{
firstName: "John"
ID: "10"
},
{
firstName: "Mary"
ID: "20"
}
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句