user2350086
user2350086

Reputation: 111

Cannot read property of undefined when accessing next element of array

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?

Upvotes: 0

Views: 162

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

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

Upvotes: 1

Related Questions