Wallace Brown
Wallace Brown

Reputation: 612

Why do javascript objects output as "undefined" when looping through an array?

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);
}

Upvotes: 3

Views: 4347

Answers (4)

MatuDuke
MatuDuke

Reputation: 5008

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?

Upvotes: 0

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

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

Upvotes: 1

Niko
Niko

Reputation: 26730

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

for (date in dates) {
    alert('after: ' + dates[date].beginDate ...);
}

Upvotes: 0

Pointy
Pointy

Reputation: 413737

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!

Upvotes: 6

Related Questions