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?

3
  • 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. Commented Jun 4, 2021 at 22:42
  • 3
    you can add console.log(typeof i) in the loop and find out that i is a string Commented Jun 4, 2021 at 22:45
  • Does this answer your question? Adding two numbers concatenates them instead of calculating the sum Commented Jun 4, 2021 at 22:52

1 Answer 1

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

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

1 Comment

Thank you. I understand now.

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.