【发布时间】:2019-02-18 22:28:04
【问题描述】:
我订阅了一个以 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')。
【问题讨论】:
-
稍微搜索一下;实际上有数百个关于从对象数组中求和值的问题。
标签: javascript html json api