【问题标题】:Why I'm getting undefined when I tried to access the element from nested array in javascript?当我尝试从 javascript 中的嵌套数组访问元素时,为什么我会变得未定义?
【发布时间】:2019-09-06 14:06:23
【问题描述】:

我正在尝试从 javascript 中的多维数组中访问元素。当我尝试使用变量从数组中的数组访问元素时,我得到undefined 结果。如果我使用数字而不是变量,我会得到结果..

let arr = [[1,2,3],[4,5,6],[7,8,9]];

for(let i=0; i < arr.length; i++) {
  console.log(arr[i][arr.length]);
}

【问题讨论】:

  • 因为 arr[0][3] 不存在 (arr.length = 3)

标签: javascript arrays multidimensional-array nested


【解决方案1】:

因为数组的长度是3,而你的最后一个数组索引是2。你可以修改它:

let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0;i<arr.length;i++){
  console.log(arr[i][arr.length - 1]); // Note the -1
}

这将返回3, 6, 9

【讨论】:

    【解决方案2】:

    如果您想访问嵌套数组中的所有元素,您将需要两个 for 循环,一个用于迭代第一层,另一个循环用于迭代内部层。

    let arr = [[1,2,3],[4,5,6],[7,8,9]];
    
    for(let i=0; i < arr.length; i++) {
      //looping through the outer array
      console.log(arr[i])
      for(let j=0;j< arr[i].length;j++)
      {
        //looping through the inner arrays
        console.log(arr[i][j]);
      }
      
    }

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多