我执行以下操作时无法读取属性'length'错误

时间:2014-08-28 08:07:55

标签: javascript

当我执行以下操作时,它显示Uncaught TypeError:无法读取属性' length'未定义的。 任何人都可以帮助我。

var events = [
  {
    "EventsCalendarID": 21,
    "AdminUserName": "ManjitSingh",
    "StartDate": "2014-08-27 12:00 AM",
    "EndDate": "8/28/2014 12:00:00 AM",
    "Timezone": "Europe/London",
    "Message": "mabkja",
    "IsApproved": true,
    "UserID": "70348398-9b8e-48a2-bbfc-c2474146d5d5",
    "User": null
  },
  {
    "EventsCalendarID": 22,
    "AdminUserName": "ManjitSingh",
    "StartDate": "2014-08-29 12:00 AM",
    "EndDate": "8/29/2014 1:00:00 AM",
    "Timezone": "Europe/London",
    "Message": "ffd",
    "IsApproved": true,
    "UserID": "70348398-9b8e-48a2-bbfc-c2474146d5d5",
    "User": null
  },
  {
    "EventsCalendarID": 23,
    "AdminUserName": "ManjitSingh",
    "StartDate": "2014-08-29 12:00 AM",
    "EndDate": "8/29/2014 1:00:00 AM",
    "Timezone": "Europe/London",
    "Message": "fndmms",
    "IsApproved": true,
    "UserID": "70348398-9b8e-48a2-bbfc-c2474146d5d5",
    "User": null
  }
];

function success(events) {
  var ev = [];
  $.each(events.items, function (i, v) {
    ev.push({
      title: v.Message,
      start:v.StartDate,
      end:v.EndDate,
      id: v.EventsCalendarID
    });
  });
}

2 个答案:

答案 0 :(得分:3)

看起来错误就在这一行

                $.each(events.items, function (i, v) {

这将迭代events.items,这是未定义的(因为events只是一个数组,它没有属性items)。 $.each尝试阅读属性events.items.length,尝试迭代events.items,这解释了您的错误。可能你想改为:

                $.each(events, function (i, v) {

答案 1 :(得分:3)

除了arghbleargh所说的(这也是正确的),你也可以(或者)使用

events.forEach(function (i, v) {
    ev.push({ title: i.Message, start: i.StartDate, end: i.EndDate, id: i.EventsCalendarID });
});

这是我用过的小提琴http://jsfiddle.net/ymrsxh2h/

希望这也有助于:)