我将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"}
。如何在每次刷新页面时避免数据成倍增加?
答案 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);
}