[英]Just trying to store 6 array values into localStorage
The array oldData [] holds 6 values.数组 oldData [] 包含 6 个值。 (integer values fetched from api).
(从 api 获取的整数值)。 All I want to do is put these values in 1 localStorage key called 'olddata'.
我想要做的就是将这些值放在名为“olddata”的 1 个 localStorage 键中。
I've searched everywhere and didn't find anything that make this work.我到处搜索,但没有找到任何使这项工作有效的东西。 Could please someone help me with a simple solution?
请有人帮我提供一个简单的解决方案吗?
The way I'm trying now:我现在尝试的方式:
let oldData = [];
oldData.push(parkingData.availableCapacity);
console.log(oldData); // Definitely holds 6 values
localStorage.setItem('olddata', oldData); // Only stores the last value
of oldData
Also tried a few loops but didn't succeed.也尝试了几个循环但没有成功。
localStorage
only stores strings. localStorage
只存储字符串。
Use JSON.stringify()
to set an array as string and JSON.parse()
to parse that same string back to array when you retrieve the data使用
JSON.stringify()
将数组设置为字符串,使用JSON.parse()
在检索数据时将相同的字符串解析回数组
localStorage.setItem('olddata', JSON.stringify(oldData));
let url = 'https://datatank.stad.gent/4/mobiliteit/bezettingparkingsrealtime.json#';
let percent;
let mainDiv = document.getElementById('mainDiv');
function fetchParkingData() {
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
mainDiv.innerHTML = "";
for(let i = 0; i < data.length; i++) {
let parkingData = {
name: data[i].name,
totalCapacity: data[i].parkingStatus.totalCapacity,
availableCapacity: data[i].parkingStatus.availableCapacity,
}
let oldData = [];
oldData.push(JSON.parse(parkingData.availableCapacity));
console.log(oldData);
// console.log(oldData.join());
localStorage.setItem('dataObject', JSON.stringify(oldData));
};
})
.catch(function(error) {
// error handling
parkingDiv.innerHTML = 'Data could not be fetched';
});
}
Browser console commands and output here:浏览器控制台命令和输出在这里:
>let oldData = [];
undefined
>oldData.push('1st Value');
1
>oldData.push('2nd Value');
2
>oldData.push('3rd Value');
3
>console.log(oldData);
(3) ["1st Value", "2nd Value", "3rd Value"]
undefined
>localStorage.setItem('oldData', JSON.stringify(oldData));
undefined
>JSON.parse(localStorage.getItem('oldData'));
(3) ["1st Value", "2nd Value", "3rd Value"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.