[英]Just trying to store 6 array values into localStorage
數組 oldData [] 包含 6 個值。 (從 api 獲取的整數值)。 我想要做的就是將這些值放在名為“olddata”的 1 個 localStorage 鍵中。
我到處搜索,但沒有找到任何使這項工作有效的東西。 請有人幫我提供一個簡單的解決方案嗎?
我現在嘗試的方式:
let oldData = [];
oldData.push(parkingData.availableCapacity);
console.log(oldData); // Definitely holds 6 values
localStorage.setItem('olddata', oldData); // Only stores the last value
of oldData
也嘗試了幾個循環但沒有成功。
localStorage
只存儲字符串。
使用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';
});
}
瀏覽器控制台命令和輸出在這里:
>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.