You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化JavaScript对象数组中最大值与最小值的获取代码?

简化获取数组对象中金额的最大/最小值

你的原有代码逻辑没问题,但可以利用JavaScript的数组方法和Math对象的静态方法大幅简化代码,以下是几种优化方案:

方案一:提取值数组 + 扩展运算符(简洁直观)

先通过map提取所有amount值组成纯数字数组,再用Math.min和Math.max配合扩展运算符直接计算:

const skuStylePlu = [{
    skuPrice: {
      currentPrice: {
        amount: 10
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 20
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 30
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 40
      }
    }
  },
  {
    skuPrice: {
      currentPrice: {
        amount: 50
      }
    }
  }
];

const amounts = skuStylePlu.map(item => item.skuPrice.currentPrice.amount);
const lowest = Math.min(...amounts);
const highest = Math.max(...amounts);

console.log(lowest, highest); // 输出 10, 50

方案二:避免扩展运算符的栈溢出风险(适合超大数组)

如果数组元素数量极多,扩展运算符可能导致栈溢出,此时可以用apply方法传递数组参数:

const amounts = skuStylePlu.map(item => item.skuPrice.currentPrice.amount);
const lowest = Math.min.apply(Math, amounts);
const highest = Math.max.apply(Math, amounts);

方案三:单次遍历的高性能方案(内存友好)

用reduce只遍历一次数组,无需生成中间数组,内存占用更低,适合大数据量场景:

const { lowest, highest } = skuStylePlu.reduce((acc, item) => {
  const amount = item.skuPrice.currentPrice.amount;
  return {
    lowest: Math.min(acc.lowest, amount),
    highest: Math.max(acc.highest, amount)
  };
}, { lowest: Number.POSITIVE_INFINITY, highest: Number.NEGATIVE_INFINITY });

console.log(lowest, highest); // 输出 10, 50

内容的提问来源于stack exchange,提问作者Katyellen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:31:15