【发布时间】:2014-01-23 01:26:24
【问题描述】:
我正在尝试将 localStorage 值存储在数组中并关注此页面 Push JSON Objects to array in localStorage。我的代码是:
function SaveDataToLocalStorage(data)
{
var a = [];
// Parse the serialized data back into an aray of objects
a = JSON.parse(localStorage.getItem('session'));
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
data 在哪里:
var data = {name: "abc", place: "xyz"}
我收到以下错误:
Uncaught TypeError: Cannot call method 'push' of null
谁能展示在数组中存储 localStorage 值的正确方法?
【问题讨论】:
-
变量“a”必须为空。在您的浏览器中使用调试器并在运行推送调用之前检查该值。我认为这应该让你走上正轨
标签: javascript arrays json html local-storage