3

You can see a working example here:

http://jsfiddle.net/bwhitney/ZDHp4/1/

I am trying to create an array of objects in javascript. When I attempt to access the objects I am getting "undefined" output. Here is some sample code:

var dates = [];

var beginDate1 = new Date("01 / 01 / 01");
var endDate1 = new Date("02 / 02 / 02");
var beginDate2 = new Date("03 / 03 / 03");
var endDate2 = new Date("04 / 04 / 04");

// this outputs the correct dates
alert("before: " + beginDate1 + "--" + endDate1);
alert("before: " + beginDate2 + "--" + endDate2);

dates.push({
    "beginDate": beginDate1,
    "endDate": endDate1
}, {
    "beginDate": beginDate2,
    "endDate": endDate2
});

var date;
for (date in dates) {
    // this outputs "date: undefined--undefined"
    // why would that be?
    alert("after: " + date.beginDate + "--" + date.endDate);
}
Wallace Brown
  • 612
  • 6
  • 17

4 Answers4

6

The for ... in loop in JavaScript gives you the keys in the object, not the values.

You really should use a numeric index however:

for (var date = 0; date < dates.length; ++date) {
  alert("date " + date + " is: " + dates[date]);
}

Iterating over keys with for ... in will not pick up only the numerically-indexed array elements; it operates on arrays as if they are plain ordinary objects. Other properties will be picked up too, plus you're not even guaranteed it'll go in ascending numeric order!

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I see. So the for loop using array index is what I really want here. Thanks for the tip about ascending numeric order as well. – Wallace Brown Jun 07 '12 at 19:45
1

Common mistake in for each loop. date is index of dates. You should write: dates[date].beginDate.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66
0

When using a for..in loop, the variable gets assigned the key, not the value!

for (date in dates) {
    alert('after: ' + dates[date].beginDate ...);
}
Niko
  • 26,516
  • 9
  • 93
  • 110
0

for ... in doesn't work like that with arrays, you can use a regular for like this fiddle: http://jsfiddle.net/bwhitney/ZDHp4/1/

Reference: Why is using "for...in" with array iteration a bad idea?

Community
  • 1
  • 1
MatuDuke
  • 4,997
  • 1
  • 21
  • 26