在localstorage的帮助下存储数据

时间:2014-01-28 15:43:27

标签: javascript html5 local-storage

我将localstorage数据存储在数组中。我的代码是:

 var a;
//is anything in localstorage?
if (localStorage.getItem('session') === null) {
    a = [];
} else {
     // Parse the serialized data back into an array 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);
  document.write(a + "<br>")
 // 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"}

每次刷新页面时,我的数据都会成倍增加:

[{name: "abc", place: "xyz"}, {name: "abc", place: "xyz"}, {name: "abc", place: "xyz"}, {name: "abc", place: "xyz"}]

我想仅在data值变化而不是{name: "abc", place: "xyz"}时才存储数据,我有{name: "ijk", place: "uvx"}。如何在每次刷新页面时避免数据成倍增加?

1 个答案:

答案 0 :(得分:0)

在插入新数据之前,您必须先查看a

if (!a.some(filterData(data)) {
  a.push(data);
}

function filterData(data) {
  return function(item) {
    return item.name === data.name && item.place === data.place;
  };
}

你可以用循环实现同样的目的:

var found = false;
for (var i = a.length; i--;) {
  if (a[i].name === data.name && a[i].place === data.place) {
    found = true;
    break;
  }
}

if (!found) {
  a.push(data);
}