繁体   English   中英

无法使用 javascript 将数组存储在本地存储中

[英]Unable to store array in local Storage using javascript

所以基本上我正在尝试创建从中存储一些用户信息在本地存储和更新和删除用户的信息我刚刚开始处理它但卡在本地存储中插入完整的用户数据。 每当我将用户数据存储在本地存储中时(对象:对象)。

<!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"
    }
]

由于 localStorage 只处理字符串,你需要使用 JSON.parse/JSON.stringify 如下

function myFunction(){     
    var fname = document.getElementById("fname").value;  
    var id = document.getElementById("id").value;  

    if (typeof(Storage) !== "undefined") {
        // note: using {} ... person is an Object, not an Array
        var person = {firstName: fname , ID : id  };

        // use JSON.parse to parse the string to an Object 
        var tempitem =JSON.parse(localStorage.getItem("record") || "[]");
        // || [] so of it doesn't exist, returns an empty array to push to
        tempitem.push(person);

        // stringify the Object to store as a string
        localStorage.setItem("record",  JSON.stringify(tempitem));
    }
}

localStorage 将项目存储在字符串中,因此在您的情况下,您应该这样做:

localStorage.setItem("record", JSON.stringify(tempitem))

如果你想从 localStorage 获取它,你可以:

JSON.parse(localStorage.getItem('record'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM