如何获取数组最大值及对应名称,以及API数据中的最高身高与对应姓名
解决方法:从SWAPI数据中获取最高身高及对应姓名
嘿,我来帮你搞定这个问题!首先得说清楚:你当前调用的https://swapi.co/api/species/1/是「人类」这个物种的数据,里面的people字段是该物种下所有人物的API链接列表。所以第一步得先拉取这个物种数据,再批量拉取所有人物的详细信息,之后才能统计最高身高。
步骤1:批量拉取所有人物数据
先调整你的数据拉取逻辑,支持批量获取人物信息:
const speciesUrl = 'https://swapi.co/api/species/1/'; // 先拉取物种数据,再批量拉取该物种下的所有人物 async function fetchAllPeopleFromSpecies(url) { const speciesData = await fetch(url).then(resp => resp.json()); // 把每个人物的API链接转成fetch请求,再批量执行 const peoplePromises = speciesData.people.map(personUrl => fetch(personUrl).then(resp => resp.json())); return Promise.all(peoplePromises); }
步骤2:找出最高身高的人物
接下来处理拿到的人物数组——注意SWAPI里的height是字符串,还有些是"unknown"(未知),所以得先过滤掉无效数据,把有效身高转成数字,再用reduce方法找到最高的那个人:
function findTallestPerson(peopleArray) { // 过滤掉身高未知的,同时把身高转成数字类型 const validPeople = peopleArray .filter(person => person.height !== 'unknown') .map(person => ({ ...person, height: Number(person.height) })); if (validPeople.length === 0) { return null; // 万一所有身高都是未知的情况 } // 用reduce遍历数组,每次保留当前最高的人物 return validPeople.reduce((tallest, current) => { return current.height > tallest.height ? current : tallest; }, validPeople[0]); }
步骤3:整合调用,输出结果
把上面的函数串起来,调用后就能拿到结果了,还能把结果加到你的表格里:
fetchAllPeopleFromSpecies(speciesUrl) .then(people => { const tallestPerson = findTallestPerson(people); if (tallestPerson) { console.log(`最高的人物是:${tallestPerson.name},身高${tallestPerson.height}cm`); // 你也可以在这里给表格加一行,把这个统计结果展示出来 } else { console.log('没找到有效的身高数据'); } }) .catch(err => console.error('拉取数据出错啦:', err));
通用技巧:找数组中最大值及对应名称
如果你以后还要找其他字段的最大值(比如体重mass),可以封装一个通用函数,复用性更强:
function findMaxItem(arr, valueKey, nameKey = 'name') { // 先过滤并转换有效数据 const validItems = arr .filter(item => { const value = item[valueKey]; return typeof value === 'number' || (!isNaN(Number(value)) && value !== 'unknown'); }) .map(item => ({ ...item, [valueKey]: Number(item[valueKey]) })); if (validItems.length === 0) return null; // 用reduce找出最大值对应的元素 return validItems.reduce((maxItem, currentItem) => { return currentItem[valueKey] > maxItem[valueKey] ? currentItem : maxItem; }, validItems[0]); } // 举个例子:找体重最重的人物 const heaviestPerson = findMaxItem(people, 'mass'); if (heaviestPerson) { console.log(`体重最重的是:${heaviestPerson.name},体重${heaviestPerson.mass}kg`); }
小提醒
- 一定要把字符串类型的数值转成数字再比较!不然会出现
"20"比"190"大的尴尬情况(字符串是按字符顺序比的) - 记得处理
unknown或者非数值的情况,避免代码报错 - 如果有好几个人身高一样高,上面的方法会返回第一个遇到的最高者;要是想返回所有最高的,可以先找出最大值,再过滤数组里等于这个值的元素
内容的提问来源于stack exchange,提问作者MikeL5799
相关产品推荐
相关产品推荐

