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

如何使用JavaScript从JSON数组中获取最大speed值

提取JSON数组中最高speed值的JavaScript方案

这里提供两种简洁高效的方法来提取目标数组中的最大speed值:

方法1:Array.map() + Math.max()

先将数组中每个对象的speed属性提取为单独的数值数组,再用Math.max()获取最大值:

// 假设已将JSON解析为data变量
const data = [
  // 你的JSON数组内容
];

// 提取所有speed值
const speedList = data.map(item => item.speed);
// 计算最大值
const highestSpeed = Math.max(...speedList);

console.log(highestSpeed); // 输出:69

方法2:Array.reduce()

直接遍历数组并逐个比较,无需额外生成数组,性能更优:

const data = [
  // 你的JSON数组内容
];

const highestSpeed = data.reduce((currentMax, item) => {
  return item.speed > currentMax ? item.speed : currentMax;
}, 0); // 初始值设为0,适用于speed非负的场景

console.log(highestSpeed); // 输出:69

处理空数组的边界情况

如果数组可能为空,需要添加判断避免错误:

const data = [];

// 方法1的空数组兼容
const speedList = data.map(item => item.speed);
const highestSpeed = speedList.length ? Math.max(...speedList) : null;

// 方法2的空数组兼容
const highestSpeed = data.length 
  ? data.reduce((max, item) => item.speed > max ? item.speed : max, data[0].speed)
  : null;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:05:24