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

JavaScript算法:索引差值为负时返回尽可能多的有效数组元素

你现有代码的逻辑错误在起始索引的边界处理:当initialIndex - extraCount 小于0时,你设置start = initialIndex,会直接跳过从数组开头到初始索引前的所有有效元素,导致返回结果缺失前置元素。

正确代码实现

function algorithm(data, initialIndex, extraCount) {
  // 起始索引最小取0,过滤负索引场景
  const start = Math.max(0, initialIndex - extraCount);
  // slice为左闭右开,结束索引取初始索引+1才能包含初始索引对应的元素
  const end = initialIndex + 1;
  return data.slice(start, end);
}

验证测试用例

用你给出的所有示例验证,结果完全符合要求:

  • algorithm([0,1,2,3,4,5], 2, 1) → [1,2]
  • algorithm([0,1,2,3,4,5], 4, 3) → [1,2,3,4]
  • algorithm([0,1,2,3,4,5], 1, 2) → [0,1]
  • algorithm([0,1,2,3,4,5], 2, 5) → [0,1,2]
  • algorithm([0,1,2,3,4,5], 0, 10) → [0]
  • algorithm([0,1,2,3,4,5], 3, 7) → [0,1,2,3]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:18:03