簡體   English   中英

當我嘗試從javascript中的嵌套數組訪問元素時,為什么會變得未定義?

[英]Why I'm getting undefined when I tried to access the element from nested array in javascript?

我正在嘗試從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]);
}

因為數組的長度為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

如果要訪問嵌套數組中的所有元素,則需要兩個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]); } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM