0
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]);
  }
}
1
  • 1
    arr.length is 3 in your example. Which means that only arr[0],arr[1] and arr[2] have a value. Your for loop correctly includes 0 (condition is i>=0, not i<0), but incorrectly starts with i=3, which is not a valid index Commented Oct 1, 2022 at 17:37

1 Answer 1

1

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]);
  }
}

Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much brother....i am learning the basics of JS ....but i have stuck with this problem since 2 hours .....but you solved it ..thank u thank u ...
I would personally ask a question here only after days of research meta.stackoverflow.com/questions/261592/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.