Home > Blockchain >  Undefined when reading length with nested for loops in JAVA SCRIPT
Undefined when reading length with nested for loops in JAVA SCRIPT

Time:10-02

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

for (let i=arr.length;i>=0;i--){
  console.log(arr[i]);
  for (let n=arr[i].length;n>=0;n--){
    console.log(arr[i][n]);
  }
}

CodePudding user response:

You are trying to read out of range of arrays. Add -1

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

for (let i = arr.length - 1; i >= 0; i--) {
  console.log(arr[i]);
  for (let n = arr[i].length - 1;/* While accessing index, always consider `length - 1` */ n >= 0; n--) {
    console.log(arr[i][n]);
  }
}

  • Related