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);
}
The
for ... inloop in JavaScript gives you the keys in the object, not the values.You really should use a numeric index however:
Iterating over keys with
for ... inwill 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!