-1

So in my program, I have an array that contains a dictionary/hash of values and when I loop through the array, I get the value I need but any code after the for loop does not get executed because the console outputs:

TypeError: array[i] is undefined


var array = [
  {"name": "a", "pos": "C"},
  {"name": "b", "pos": "B"},
  {"name": "c", "pos": "W"},
];


for(var i = 0; i <= array.length; i++) {
  console.log(array[i]['pos'];
}
console.log("some other code");

I don't understand why this happens and I need the code underneath the for loop to execute. Does anyone know why this happens and what I should do to fix it?

Jeebs600
  • 269
  • 2
  • 7

1 Answers1

2

Issues

  1. You haven't enclosed your first console.log function.
  2. As an array is zero indexed making your condition less than or equal to will make the loop try to use an undefined part of the array (bigger than total length). Therefore use the less than operator.

Fixed code

var array = [
  {"name": "a", "pos": "C"},
  {"name": "b", "pos": "B"},
  {"name": "c", "pos": "W"},
];


for(var i = 0; i < array.length; i++) {
  console.log(array[i]['pos']);
}

console.log("some other code");
Borys
  • 21
  • 4