如何将对象推入数组并存储在localstorage中

时间:2018-03-12 13:05:49

标签: javascript

这是我的对象

var studentObject = {
        "REG_NO": regNo,
        "NAME": name,
        "SSC": ssc,
        "HSC": hsc,
        "GRADUATION": graduate
 };

这是我的空数组

var tableDisplay = [];

将studentObject推送到tableDisplay数组并将其存储在localStorage中,它应该采用这种格式

[
{
"REG_NO": regNo,
"NAME": name,
"SSC": ssc,
"HSC": hsc,
"GRADUATION": graduate
}
]

1 个答案:

答案 0 :(得分:4)

将对象推入数组:

tableDisplay.push(studentObject);

要将其存储在localStorage中,您必须对其进行字符串化:

localStorage.setItem("tableDisplay", JSON.stringify(tableDisplay));

然后在检索它时解析它:

tableDisplay = JSON.parse(localStorage.getItem("tableDisplay"));