最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

You can see a working example here:

/

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

You can see a working example here:

http://jsfiddle/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);
}
Share Improve this question asked Jun 7, 2012 at 19:37 Wallace BrownWallace Brown 6126 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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!

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

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

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

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

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

发布评论

评论列表(0)

  1. 暂无评论