var myjsonObj = '[{"location":"Helsinki", "temperature":4},
{"location":"Tokyo", "temperature":26}]';
var jsObj = JSON.parse(myjsonObj);
console.log(jsObj[0].location);
console.log(jsObj[0].temperature);
var observationsArray = [];
function init() {
if (localStorage.observationsRecord) {
observationsArray = JSON.parse(localStorage.observationsRecord);
for (var i = 0; i < observationsArray.length; i++) {
prepareTableCell(observationsArray[i].location, observationsArray[i].temperature);
}
}
}
function onRegisterPressed() {
var locationName = document.getElementById("location").value;
var temperatureValue = document.getElementById("temperature").value;
var stuObj = {
location: locationName,
temperature: temperatureValue
};
observationsArray.push(stuObj);
localStorage.observationsRecord = JSON.stringify(observationsArray);
prepareTableCell(locationName, temperatureValue);
document.getElementById("location").value = "";
document.getElementById("temperature").value = "";
}
function prepareTableCell(locationName, temperatureValue) {
var table = document.getElementById("regtable");
var row = table.insertRow();
var locationNameCell = row.insertCell(0);
var temperatureValueCell = row.insertCell(1);
locationNameCell.innerHTML = locationName;
temperatureValueCell.innerHTML = temperatureValue;
//firstNameCell.colSpan = 2;
}
你好!我是网络开发的新手,我一直在关注TechThree INFO的youtube频道指南。我创建了一个html表单,将数据提交到本地存储。我的下一步是显示指定位置(过去24小时)的最低和最高温度,以及每个位置的当前温度。我目前对如何显示本地存储的数据一无所知。
要从localStorage获取数据,您可以使用localStorage.getItem(key)
这将返回您的字符串化JSON,因此您需要将其解析回JS对象。
var observations = JSON.parse(localStorage.getItem('observationsRecord'))
最后,您想要找到最高和最低温度。
var max = {
location: '',
temperature: 0
};
var min = {
location: '',
temperature: 0
};
for(var i = 0; i < observations.length; i++) {
if(observations[i].temperature > max) {
max.location = observations[i].location;
max.temperature = observations[i].temperature;
}
if(observations[i].temperature < min) {
max.location = observations[i].location;
min.temperature = observations[i].temperature;
}
}
您的最高温度将以最大值存储,最低温度以最小值存储。
希望这可以帮助 :)