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

如何用非嵌套数组作为嵌套数组的索引键?

用数组作为嵌套数组的索引链实现方法

原生JavaScript不支持直接将数组作为嵌套数组的索引链使用,比如arr1[arr2]这种写法无法自动逐层访问嵌套元素。但你可以通过自定义工具函数来实现这个需求。

实现方案:使用reduce方法

最简洁的方式是利用数组的reduce方法,遍历索引数组逐层访问嵌套元素:

function getNestedValue(nestedArr, indices) {
  return indices.reduce((currentLayer, index) => {
    // 增加边界判断,防止访问不存在的层级或索引导致报错
    if (!Array.isArray(currentLayer) || index >= currentLayer.length) {
      return undefined;
    }
    return currentLayer[index];
  }, nestedArr);
}

// 测试示例(注意:原示例中arr2=[3,0]对应arr1[3][0]即'e',若要取'c'需改为[2,0])
var arr1 = ['a', 'b', ['c', 'd'], ['e', 'f']];
var arr2 = [2, 0]; // 对应 arr1[2][0],返回 'c'
var arr3 = [3, 1]; // 对应 arr1[3][1],返回 'f'

console.log(getNestedValue(arr1, arr2)); // 输出 'c'
console.log(getNestedValue(arr1, arr3)); // 输出 'f'

函数说明

  • reduce会从嵌套数组的最外层开始,依次使用索引数组中的每一个值,逐层深入到嵌套结构内部。
  • 加入的边界判断可以避免因索引越界或层级不存在而抛出错误,此时会返回undefined。

补充:递归实现(可选)

如果你更习惯递归写法,也可以这样实现:

function getNestedValueRecursive(nestedArr, indices) {
  if (indices.length === 0) return nestedArr;
  const [currentIndex, ...restIndices] = indices;
  if (!Array.isArray(nestedArr) || currentIndex >= nestedArr.length) {
    return undefined;
  }
  return getNestedValueRecursive(nestedArr[currentIndex], restIndices);
}

// 测试
console.log(getNestedValueRecursive(arr1, arr2)); // 输出 'c'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:40:42