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

标签 javascript arrays json promise fetch

我有一个从 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/

相关文章:

javascript - 用于 appjs 应用程序的 Splash

java - 破坏二进制文件

ios - 数组在函数中填充并显示但在 tableview swift 中不显示

php - 拆分数组以获得供应商权重 - PHP -

javascript - 如何使用 api 设置要翻译的文本值

java - 使用 Jackson 解析动态生成的 JSON 对象名称

php - 从 MySQL 获取数据并使用 JSON 在 ListView 中显示

javascript - Selenium:元素不可点击……其他元素会收到点击,还是点击

javascript - less.js : Use custom import function

javascript - 在 div 中动态插入 React 组件