在我的应用程序中,我有2个函数可以使用localStorage。 当我添加第一个和第二个项目时,它可以正常工作,但是当它是第三个项目时,它会给出错误。
以下是功能:
w.getLocalStorage = function() {
var c = localStorage.getItem('cities');
var arr = [];
arr.push(c);
return c ? arr : [];
}
w.setLocalStorage = function(data, googleData, cities, name) {
if (data) {
city.name = data.name;
city.coord.lat = data.coord.lat;
city.coord.lon = data.coord.lon;
cities.push(JSON.stringify(city));
// console.log(city);
localStorage.setItem("cities", cities);
} else if (googleData) {
city.name = name;
city.coord.lat = googleData.results[0].geometry.location.lat;
city.coord.lon = googleData.results[0].geometry.location.lng;
console.log('cities', cities);
cities.push(JSON.stringify(city));
// console.log(cities, city);
localStorage.setItem("cities", cities);
}
}
以下是前两项的回报:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
以下是添加第三项时的内容:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}, {"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
我该如何解决这个问题?
答案 0 :(得分:1)
由于您只能在localStorage
中存储字符串,因此持久化对象使用JSON.stringify()
方法将其转换为字符串格式,并在检索时使用JSON.parse()
来解析JSON字符串以构造JavaScript值或对象。
以下是需要注意的代码段。您应该保留字符串化的cities
数据
cities.push(city);
localStorage.setItem("cities", JSON.stringify(cities));
检索时,将其解析为JavaScript对象
var cities = localStorage.getItem('cities');
var c = cities ? JSON.parse(cities) || [];