如何简化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
相关产品推荐
相关产品推荐

