【问题标题】:Getting the max for an Api json data in react在反应中获取 Api json 数据的最大值
【发布时间】:2022-01-04 00:20:21
【问题描述】:

我已经获取了一个“价格”的 Api 数据,我正在尝试获得最大的值,但是这个功能不起作用,我将不胜感激!

const pricedata = {
    datasets: [
        {
            backgroundColor: '#0000',
            barPercentage: 2,
            barThickness: 5,
            data: PRICES,
            label: 'Update in prices',
            maxBarThickness: 10
        },
    ],
};

function findMax(PRICES) {
    if (!PRICES) {
        return;
    }
    return Math.max(...PRICES);
}

console.log(findMax())

【问题讨论】:

  • PRICES变量的值是多少?
  • @Dylan 它的数字
  • @Dylan 是的

标签: reactjs json api dataset max


【解决方案1】:

我在数据中有 PRICES 的地方添加了“价格数据”,并添加了第二组数据用于说明。

下面的代码循环遍历每个“数据集”,找到最高价格并将其添加为一个名为“maxPrice”的新键。然后将它们打印出来。这只是一种方式。

const pricedata = {
  datasets: [
    {
      backgroundColor: "#0000",
      barPercentage: 2,
      barThickness: 5,
      data: [1, 10, 30, 7, 42, 12],
      label: "Update in prices",
      maxBarThickness: 10
    },
    {
      backgroundColor: "#0000",
      barPercentage: 2,
      barThickness: 5,
      data: [11, 70, 18, 17, 24, 12],
      label: "Update in prices",
      maxBarThickness: 10
    }
  ]
};

function findMax(PRICES) {
  if (!PRICES) {
    return 0;
  }
  return Math.max(...PRICES);
}

pricedata.datasets.forEach((dataset) => {
  dataset.maxPrice = findMax(dataset.data);
});

pricedata.datasets.forEach((dataset) => {
  console.log('max price is', dataset.maxPrice);
});

更新: 使用减速器获得所有产品的最大值...

const maxOfAllProducts = pricedata.datasets.reduce((accumulator, current) => Math.max(current.maxPrice, accumulator),0);
console.log('max of all products', maxOfAllProducts)

【讨论】:

    【解决方案2】:

    您忘记将 PRICES 变量放在最后一行的函数调用中

      let PRICES = [1,2,3,4,5,6,7,8,9,10];
     
    
      function findMax(PRICES) {
        if (!PRICES) {
            return;
        }
        return Math.max(...PRICES);
    }
    
    console.log(findMax(PRICES)) // outputs 10
    

    或者删除函数中的那个变量

      let PRICES = [1,2,3,4,5,6,7,8,9,10];
     
    
      function findMax() {
        if (!PRICES) {
            return;
        }
        return Math.max(...PRICES);
    }
    
    console.log(findMax()) //outputs 10
    
    

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 2021-12-24
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2021-05-23
      • 2021-07-20
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多