2

When I run the below JavaScript code the first two lines of output are:

5
undefined

Why is the second output line undefined and not 5? Here is the code:

matrix = [
  [2, 5, 7],
  [4, 6, 1],
  [7, 3, 9]
];
for (var i in matrix) {
  for (var j in matrix[i]) {
    console.log(matrix[0][0 + 1]);
    console.log(matrix[i][j + 1]);
  }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
okcapp
  • 405
  • 1
  • 4
  • 15
  • 5
    Don't use `for...in` with arrays, it hould be used with objects, in your code both `i` and `j` are strings, so `j + 1` will not be what you expect it to be. It also loops the array out of order – ibrahim mahrir Jan 02 '19 at 02:41
  • Because `j` is the string `"0"`. `"0" + 1` is `"01"`, not `1`. Related: [Javascript - For Loop key undefined ONLY for 1st iteration?](https://stackoverflow.com/q/22182453/4642212). – Sebastian Simon Jan 02 '19 at 02:43
  • 1
    It’s also explained here, in [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/a/1365581/4642212). – Sebastian Simon Jan 02 '19 at 02:52
  • @Xufox The link you shared solved the problem. Thanks... – okcapp Jan 02 '19 at 03:09

2 Answers2

0

oNot sure why you are trying to +1. This is causing your issue. Also included array.forEach of this as well.

Included fix based on Ibrahim comment

matrix = [[2, 5, 7], [4, 6, 1], [7, 3, 9]];
for(let i of  matrix){
    for(let j of i){
        console.log(j);
    }
}

matrix.forEach(m => {
  m.forEach(e => console.log(e));
});
Bibberty
  • 4,670
  • 2
  • 8
  • 23
0

You have to cast your j variable to integer using Number() function.

matrix = [
  [2, 5, 7],
  [4, 6, 1],
  [7, 3, 9]
];
for (var i in matrix) {
  for (var j in matrix[i]) {
    console.log(matrix[0][0 + 1]);
    console.log(matrix[i][Number(j) + 1]);
  }
}
RAGINROSE
  • 694
  • 8
  • 13