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]);
}
}
-
1arr.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 indexchrslg– chrslg2022-10-01 17:37:31 +00:00Commented Oct 1, 2022 at 17:37
Add a comment
|
1 Answer
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]);
}
}
2 Comments
Yusuf Khan
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 ...
Konrad
I would personally ask a question here only after days of research meta.stackoverflow.com/questions/261592/…