0

I am a javascript newbie and am getting the following error on line 10 of my code: TypeError: Cannot read property '0' of undefined

var arr = [[1,7], [2,6], [3,5], [4,4], [5,3], [6,2], [7,1]];

console.log("arr[0] = ("+arr[0][0]+","+arr[0][1]+")");
console.log("arr[1] = ("+arr[1][0]+","+arr[1][1]+")");

for (var i in arr) 
{
  console.log("i = "+i);

  if (i<arr.length - 2)
  {
    console.log(i+" ("+arr[i][0]+","+arr[i][1]+")");
    console.log(i+" ("+arr[i+1][0]+","+arr[i+1][1]+")");
  }
}

The output before this error is

arr[0] = (1,7)
arr[1] = (2,6)
i = 0
0 (1,7)

So if i=0, then i+1 is 1, and arr[1][0] is defined. As it shows above arr[1][0]=2. What is my mistake?

user2350086
  • 111
  • 1
  • 8
  • 2
    Don't use `for...in` with arrays use `for...of`, `for...in` can lead to it iterating over the non-numeric properties of the array, eg functions of the array object. – Patrick Evans Jun 04 '21 at 22:42
  • 3
    you can add `console.log(typeof i)` in the loop and find out that `i` is a string – Đăng Khoa Đinh Jun 04 '21 at 22:45
  • Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – Ivar Jun 04 '21 at 22:52

1 Answers1

1

If you run the below snipet, you can see that the type of i is string

var arr = [[1,7], [2,6], [3,5], [4,4], [5,3], [6,2], [7,1]];

for (var i in arr) 
{
  console.log(typeof i); // string  
}

If i is a string and i = "0", then i + 1 is not 1 but "01" instead. And arr["01"] is undefined, so you have the error.

I suggest this version, I use the old syntax

var arr = [[1,7], [2,6], [3,5], [4,4], [5,3], [6,2], [7,1]];
for (var i = 0; i < arr.length; i = i + 1) 
{
  console.log("i = "+i);

  if (i<arr.length - 2)
  {
    console.log(i+" ("+arr[i][0]+","+arr[i][1]+")");
    console.log(i+" ("+arr[i+1][0]+","+arr[i+1][1]+")");
  }
}
Đăng Khoa Đinh
  • 5,038
  • 3
  • 15
  • 33