JavaScript嵌套结构中Math.max()的正确使用方法
如何从嵌套对象的数组中获取最大利润?
你遇到的问题核心是**Math.max()/Math.min()的传参方式错误**:这两个方法需要接收多个独立的数值参数,而不是直接传入数组。直接传数组的话,函数无法识别数组内的数值,所以返回NaN。
你的嵌套对象路径company.financials.incomeStatement.profit是完全正确的,不存在属性未定义的问题,问题出在调用Math方法的方式上。
正确实现方法:
1. 扩展运算符(推荐,ES6+)
用...把数组展开成独立参数:
console.log(Math.max(...company.financials.incomeStatement.profit)); // 输出25 console.log(Math.min(...company.financials.incomeStatement.profit)); // 输出15
2. apply()方法(兼容ES5)
通过apply()把数组作为参数列表传递:
console.log(Math.max.apply(null, company.financials.incomeStatement.profit)); // 输出25
第一个参数传null即可,因为Math.max不需要依赖this上下文。
3. 手动遍历计算(兼容旧环境)
如果需要支持更老的JS环境,可以用reduce()手动遍历数组找最大值:
const profitArr = company.financials.incomeStatement.profit; const maxProfit = profitArr.reduce((max, current) => current > max ? current : max, profitArr[0]); console.log(maxProfit); // 输出25
内容的提问来源于stack exchange,提问作者Aimee Allen
相关产品推荐
相关产品推荐

