Javascript 如何将此字符串转换回数组?

Javascript 如何将此字符串转换回数组?,javascript,arrays,nested,Javascript,Arrays,Nested,我正在尝试使用jMonthCalendar将XML提要中的一些事件添加到日历中。在原始日历中,事件位于如下所示的数组中: var events = [ { "EventID": 1, "StartDateTime": new Date(2009, 5, 12), "Title": "10:00 pm - EventTitle1", "URL": "#", "Description": "This is a sample event description", "CssClass": "Birth

我正在尝试使用jMonthCalendar将XML提要中的一些事件添加到日历中。在原始日历中,事件位于如下所示的数组中:

var events = [
{ "EventID": 1, "StartDateTime": new Date(2009, 5, 12), "Title": "10:00 pm - EventTitle1", "URL": "#", "Description": "This is a sample event description", "CssClass": "Birthday" },
{ "EventID": 2, "StartDateTime": "2009-05-28T00:00:00.0000000", "Title": "9:30 pm - this is a much longer title", "URL": "#", "Description": "This is a sample event description", "CssClass": "Meeting" }];
我使用一个循环来创建一系列事件,如下所示:

eventsArray += '{"EventID":'+eventID+', "StartDateTime": '+new Date(formattedDate)+', "EndDateTime":  '+new Date(formattedDate)+', "Title": "'+eventTitle+'", "URL": "'+detailURL+'","Description": "'+description+'"},'
然后,我尝试通过执行

eventsArray = eventsArray.slice(0, -1); var events = [eventsArray];
问题是,“eventsArray”中的内容不会像示例源代码中那样转换回数组对象


我知道这是一个noob问题,但是如果您有任何帮助,我们将不胜感激。

请尝试附加实际对象,而不是使用+=和对象的字符串版本

例如,而不是:

eventsArray += '{"EventID":'+eventID+', "StartDateTime": '+new Date(formattedDate)+', "EndDateTime":  '+new Date(formattedDate)+', "Title": "'+eventTitle+'", "URL": "'+detailURL+'","Description": "'+description+'"},'
做:


更改您的创建循环:

eventsArray.push({
  EventID: eventID, 
  StartDateTime: new Date(formattedDate), 
  EndDateTime:  new Date(formattedDate),
  Title: eventTitle, 
  URL: detailURL,
  Description: description
});

我相信,通过从字符串连接切换到直接操作对象,您将得到您想要的:

var newEvent = {"EventID": eventID, "StartDateTime": new Date(formattedDate), "EndDateTime": new Date(formattedDate), "Title": eventTitle, "URL": detailURL, "Description": description};
events.push(newEvent);

哇,谢谢!我最终使用了push而不是append,但答案很棒。谢谢
var newEvent = {"EventID": eventID, "StartDateTime": new Date(formattedDate), "EndDateTime": new Date(formattedDate), "Title": eventTitle, "URL": detailURL, "Description": description};
events.push(newEvent);