我订阅了一个以JSON格式返回数据的天气API。该数据带有多个值:
{
"success": true,
"error": null,
"response": [
{
"periods": [
{ "snowIN": 0.15 },
{ "snowIN": 0.15 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.03 },
{ "snowIN": 0.03 },
{ "snowIN": 0.03 },
{ "snowIN": 0.03 }
]
}
]
}
我想获取这些值,得到总和并在我的HTML中显示它。
我怎么做?
在48小时内获得总量降雪量
snowIN
并在html上显示该值作为文本。
我试过这个编码......
<script type="text/javascript" src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js">
</script>
<script type="text/javascript">
window.onload = () => {
const target = document.getElementById('data-reading');
const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET');
const request = aeris.api().endpoint('forecasts').place('pierre,sd').filter('1hr').limit('48');
request.get().then((result) => {
const data = result.data;
const { periods } = data[0];
if (periods) {
periods.reverse().forEach(period => {
const snowIN = period.snowIN || '0.00';
const html = (`
<p class="map-datavalue">${snowIN}"</p>
`);
target.insertAdjacentHTML('afterbegin', html);
});
}
});
}
</script>
结果显示所有snowIN
值,而不是一个。当我运行html时,我也把我的const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET')
。
你可以用Array.prototype.reduce()
来做
// Once you have the results
const api_result = {"success":true,"error":null,"response":[{"periods":[{"snowIN":0.15},{"snowIN":0.15},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.03},{"snowIN":0.03},{"snowIN":0.03},{"snowIN":0.03}]}]};
let sum;
try {
// Use reduce to calculate the sum
sum = api_result.response[0].periods.reduce((r, v) => r+v.snowIN, 0);
// JS math is not exact, so we use `toFixed` to only keep 2 decimals
sum = sum.toFixed(2);
} catch(e) {
// In case the data is not complete
sum = "not available";
}
document.getElementById('sum').innerHTML = sum;
<h1>The sum is <span id="sum"></span></h1>
您可以像这样访问数据。
const data = {"succes": true, ...}
data.response.map((value, key) => {
// value is mapping to peridos.
})
函数map()可能不是获取数据总和的绝对正确方法,但可以。 (看看MDN)我建议你先用简单的数据练习。