所以我有一个表,其中填充了来自 API 的数据。现在我想添加一个 <p>
使用数据中的平均质量 key 进行标记。这是我必须获取效果很好的表数据的代码:
const url = 'https://swapi.co/api/species/1/ ';
function fetchData(url) {
return fetch(url).then((resp) => resp.json());
}
function constructTableRow(data) {
const row = document.createElement('tr');
const { name, height, mass, hair_color } = data;
row.appendChild(constructElement('td', name))
row.appendChild(constructElement('td', height))
row.appendChild(constructElement('td', mass))
row.appendChild(constructElement('td', hair_color))
return row;
}
const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];
fetchData(url).then(data =>
data.people.forEach(personUrl =>
fetchData(personUrl).then(result => {
const row = constructTableRow(result);
swTable.appendChild(row);
})
)
);
现在这是我必须获得平均值的代码,但它不起作用:
const link = 'https://swapi.co/api/species/1/';
function fetchLink(link) {
return fetch(link).then((resp) => resp.json());
}
fetchLink(link).then(data =>
data.people.forEach(personUrl =>
fetchData(personUrl).then(result => {
const getMass = result.mass;
return getMass.reduce(function(a, b) {
return a + b;
}) / getMass.length;
})
)
);
当我运行此代码时,出现此错误:
未捕获( promise 中)类型错误:getMass.reduce 不是 fetchData.then.result 处的函数
我可以以某种方式改变它以在该提取内部运行还是我必须有一个单独的函数?
最佳答案
您的代码中存在一些未处理的问题。
首先,您尝试对每个人的质量调用.reduce
,这没有什么意义:
const getMass = result.mass;
return getMass.reduce(function(a, b) {
return a + b;
}) / getMass.length;
这就是您的 getMass.reduce is not a function
错误的来源 - .reduce
方法适用于数组,并且
例如,result.mass
是 "77"
,因此上面没有 .reduce
。
其次,人的质量不是一个数字,它实际上是一个字符串(“77”
,而不是77
),所以即使是这些质量的数组( >["87", "77", …]
) 不会得到总质量和平均质量:
["87", "77"].reduce((a, sum) => a + sum) // -> "8777"
您必须首先将这些转换为实际数字:
["87", "77"].map(a => parseInt(a)) // -> [87, 77]
[87, 77].reduce((a, sum) => a + sum) // -> 164
如果您需要十进制质量(如 "77.25"
),请使用 parseFloat
而不是 parseInt
。
此外,其中一些字符串甚至不是数字,而是“未知”
。所以你必须过滤掉它们:
["87", "77", "unknown"].filter(mass => !isNaN(mass)) // -> ["87", "77"]
这就是我的做法,希望评论能帮助您了解详细信息:
const getAvgMass = async url =>
fetch(url)
.then(r => r.json())
.then(
async data =>
(await Promise.all( // return the array after all persons are fetched and processed
data.people.map(personUrl => // take each person's URL,
fetch(personUrl) // fetch the data from it,
.then(r => r.json())
// and replace the URL in an array with person's mass
// (parseInt parses numeral strings like "77" to 77 (integer),
// and non-numeral strings like "unknown" to NaN):
.then(person => parseInt(person.mass)) // => [77, 136, 49, 120, 75, 84, 77, 84, NaN, 80, 77, NaN, …]
)
// filter out these NaNs:
)).filter(mass => !isNaN(mass)) // -> [77, 136, 49, 120, 75, 84, 77, 84, 80, 77, …]
)
// sum all masses and divide it by (filtered) array length:
.then(masses => masses.reduce((sum, x) => sum + x) / masses.length); // -> 82.77272…
// top-level await is not (yet? https://github.com/MylesBorins/proposal-top-level-await) supported
// in browsers (except Chrome console in recent versions), so to log the result, we have to do:
// getAvgMass("https://swapi.co/api/species/1/").then(result => console.log(result)); // logs 82.77272…
// or:
// const logResult = async () => console.log(await getAvgMass("https://swapi.co/api/species/1/"));
// logResult(); // logs 82.77272…
// or even:
// (async () => {
// console.log(await getAvgMass("https://swapi.co/api/species/1/")) // logs 82.77272…
// })();
// to use in a DOM element, just replace console.log:
(async () => {
const avgMass = await getAvgMass("https://swapi.co/api/species/1/");
console.log(avgMass); // logs 82.77272…
document.getElementById("sw-mass").innerText = avgMass.toFixed(2); // sets the <span> text to 82.77
})();
<p>average mass: <span id="sw-mass">…</span></p>
关于javascript - 如何计算获取请求中数据的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49671637/