gpt4 book ai didi

javascript - 如何获取数组中最大的数字和对应的名称?

转载 作者:行者123 更新时间:2023-12-03 02:08:44 25 4
gpt4 key购买 nike

我有一个从 API 提取数据的表。现在我想解析数据并获取最高的高度以及与之相关的名称。数据来自https://swapi.co/api/species/1/以下是将数据提取到表中的代码:

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 getAvgHeight = async url =>
fetch(url)
.then(r => r.json())
.then(
async data =>
(await Promise.all(
data.people.map( personUrl =>
fetch(personUrl)
.then(r => r.json())
.then(person => parseInt(person.height))
)
// filter out unkwown
)).filter(height => !isNaN(height))
)
const maxHeight = height.Math.max(height)
.then(heights => heights(maxHeight));
getAvgHeight("https://swapi.co/api/species/1/").then(result =>
document.getElementById('sw-tall').innerHTML = result.toFixed(2));

当我运行此代码时,出现错误:高度未定义

缺少什么?

最佳答案

我看到您重新使用了上一个问题/答案中的平均质量代码(获取所述人的平均质量)。这是有道理的,这个过程实际上非常相似,而且你已经快完成了。 :)

您的函数名为getAvgHeight,但它似乎试图实际获取最大高度,所以我认为这就是您的意图。

问题主要在于:

const maxHeight = height.Math.max(height)

首先,height 没有在该上下文中定义,它仅在获取人员数据期间在 Promise.all(…) 内部使用。

其次,即使您定义了高度,Math.max 也不会像这样工作:

[202, 177, 165].Math.max() // nope, arrays don't have Math at all
Math.max([202, 177, 165]) // this would make sense, sort of… but Math.max expects the actual numbers, not an array of them, and it returns NaN (because an array is not a number)
Math.max(202, 177, 165) // this works, returns 202
Math.max(...[202, 177, 165]) // this would also work, read more about it here if you want: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

您可能想阅读 Math.max 的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

因此,您可以像这样获得最大的数字(高度),但在此过程中您丢失了关联的名称。

最好按照高度对数组中的人进行排序,然后获取第一个(=最高的)。或者甚至全部排序:

const getPersonsByHeight = async url =>
fetch(url)
.then(r => r.json())
.then(
async data =>
(await Promise.all(
data.people.map(personUrl =>
fetch(personUrl)
.then(r => r.json())
.then(person => ({
// keep the name:
name: person.name,
// and height converted to integer:
height: parseInt(person.height)
})) // => { "name": "Darth Vader", "height": 202 }
)
))
.filter(person => !isNaN(person.height))
// sort array by person.height:
.sort((personA, personB) => personB.height - personA.height)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
);

/* ->
[
{
"name": "Darth Vader",
"height": 202
},
{
"name": "Qui-Gon Jinn",
"height": 193
},
{
"name": "Dooku",
"height": 193
},

]
*/

getPersonsByHeight("https://swapi.co/api/species/1/").then(people =>{
console.log(`highest: ${people[0].name}`); // people[0] is the first person, people[1] the second etc.
console.log('height chart using forEach:');
people.forEach((person, index) => console.log(`${index + 1}. ${person.name}, ${person.height} cm`))
});

关于javascript - 如何获取数组中最大的数字和对应的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49674621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com