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

JavaScript中如何通过层级索引数组获取嵌套数组对应位置的值

嵌套数组按索引路径取值问题解答

你的实现存在的问题

你代码的核心错误是reduce的初始值设置错误:你将level[0](也就是索引数组的第一个元素)作为了遍历的起点,而正确的遍历起点应该是你要取值的目标嵌套数组array本身。
按照你当前的写法,第一次执行回调时会计算level[0][level[1]],完全脱离了目标数组,自然无法得到正确结果。

正确实现方式

你可以直接把目标数组作为reduce的初始值,依次用索引数组的元素逐层取值即可:

// 通用函数,第一个参数为目标嵌套数组,第二个参数为索引路径数组
const getNestedElement = (targetArr, indexPath) => {
  return indexPath.reduce((prevLayer, currentIndex) => {
    return prevLayer[currentIndex];
  }, targetArr);
};

// 可选优化:加入可选链处理索引不存在的情况,避免报错直接返回undefined
const getNestedElementSafe = (targetArr, indexPath) => {
  return indexPath.reduce((prevLayer, currentIndex) => {
    return prevLayer?.[currentIndex];
  }, targetArr);
};

效果验证

用你给出的测试用例验证:

const array = [
    [1,2,3,4],
    [22,33,444],
    [[7],[8],[9]]
];

console.log(getNestedElement(array, [0,0])); // 输出 1
console.log(getNestedElement(array, [2,1,0])); // 输出 8

完全符合你的预期要求。


内容的提问来源于stack exchange,提问作者Андрей Мельник

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:09:03