
本文介绍如何在二维嵌套结构(如 driver[0][i].round)中快速定位指定轮次(如 round 10)出现的所有位置,返回包含驱动者索引和轮次索引的二维数组,并提供可扩展、高性能的函数实现与数据结构优化建议。
本文介绍如何在二维嵌套结构(如 `driver[0][i].round`)中快速定位指定轮次(如 round 10)出现的所有位置,返回包含驱动者索引和轮次索引的二维数组,并提供可扩展、高性能的函数实现与数据结构优化建议。
在 karting 赛事管理系统中,常需按轮次(round)反查参与该轮的驾驶员及其在数据结构中的精确位置。原始数据采用 driver[0][i] 表示第 i 位驾驶员,其 .round 属性为一维数字数组(如 [1,3,5,7,10])。需求是:给定目标轮次(例如 10),返回所有匹配项的 驱动者索引 和对应 轮次数组内的索引,组合为形如 [[driverIdx], [roundIdx]] 的二维数组。
虽然嵌套 for 循环可实现全量扫描,但面对大规模驾驶员数据(数百至数千人)时,性能与可维护性将显著下降。更优解是封装高复用性函数,并利用原生数组方法(如 indexOf、includes)提升局部查找效率。
✅ 单次匹配查找(首个出现位置)
以下函数 getRound(driverIndex, targetRound) 针对单个驾驶员快速判断目标轮次是否存在,并返回其在 .round 数组中的索引:
const getRound = (driverIndex, targetRound) => { const rounds = driver[0][driverIndex]?.round || []; const roundIndex = rounds.indexOf(targetRound); return [ [driverIndex], [roundIndex >= 0 ? roundIndex : null] ]; }; // 示例调用 console.log(getRound(1, 10)); // [[1], [4]] → driver[0][1].round[4] === 10 console.log(getRound(2, 10)); // [[2], [null]] → 未找到
⚠️ 注意:driver[0][driverIndex] 必须存在且 .round 为有效数组;使用可选链 ?. 可增强健壮性(需环境支持)。
✅ 全量匹配查找(所有出现位置)
若某驾驶员多次参与同一轮次(如因重赛、补录等场景),需获取所有匹配索引,可使用 indexOf 的 fromIndex 参数循环查找:
const getRounds = (driverIndex, targetRound) => { const rounds = driver[0][driverIndex]?.round || []; const indices = []; let i = -1; while ((i = rounds.indexOf(targetRound, i + 1)) !== -1) { indices.push(i); } return [ [driverIndex], indices ]; }; // 示例:假设 driver[0][3].round = [5, 7, 8, 10, 12, 14, 10] console.log(getRounds(3, 10)); // [[3], [3, 6]]
✅ 全局搜索:遍历所有驾驶员
要跨所有驾驶员查找 round === 10,可结合 Array.from() 与 Filter() 实现声明式遍历:
const findAllRoundMatches = (targetRound) => { const results = []; const drivers = driver[0] || []; for (let dIdx = 0; dIdx < drivers.length; dIdx++) { const rounds = drivers[dIdx]?.round || []; const rIndices = []; let i = -1; while ((i = rounds.indexOf(targetRound, i + 1)) !== -1) { rIndices.push(i); } if (rIndices.length > 0) { results.push([dIdx, rIndices]); } } // 转换为题目要求格式:[[dIdx], [rIdx1, rIdx2, ...]] return results.map(([d, rArr]) => [[d], rArr]); }; // 输出:[[[1], [4]], [[3], [3]], [[5], [1]]] console.log(findAllRoundMatches(10));
? 数据结构优化建议(面向扩展性)
当前 driver[0][i] 的二维稀疏索引方式(driver[0] 固定为第一层)不利于长期维护。推荐重构为语义化、可索引的对象结构:
// 优化后:以 driverId 为主键,支持 O(1) 查找 const drivers = { 'D001': { id: 'D001', name: 'Alice', rounds: [1,3,5,7,10] }, 'D002': { id: 'D002', name: 'Bob', rounds: [5,7,8,10,12,14] }, // ... }; // 查找更直观、可配合 Map/Set 进一步加速 const findDriversByRound = (targetRound) => Object.entries(drivers) .filter(([, d]) => d.rounds.includes(targetRound)) .map(([id, d]) => ({ driverId: id, roundIndices: d.rounds .map((r, idx) => (r === targetRound ? idx : -1)) .filter(idx => idx !== -1) }));
✅ 总结
- 对单驾驶员查找,优先使用 Array.prototype.indexOf(),时间复杂度 O(n),简洁高效;
- 对多匹配或全局搜索,避免深层嵌套 for,改用函数式迭代 + 短路逻辑;
- 当数据规模持续增长时,结构先行:将索引依赖转为语义键(如 driverId),并考虑构建倒排索引(如 roundMap[10] = [‘D001’, ‘D003’])实现 O(1) 轮次反查;
- 所有函数均应增加空值/类型校验(如 Array.isArray(rounds)),保障生产环境鲁棒性。
通过合理分层抽象与数据建模,即使驾驶员数量达万级,轮次查询仍可保持毫秒级响应。