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

时间:2010-07-08 22:51:25

标签: javascript arrays nested

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

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”中的内容不会像示例源中那样转换回数组对象。

我知道这是一个菜鸟问题,但任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:1)

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

例如,而不是:

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

执行:

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

答案 1 :(得分:0)

更改创建循环:

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

答案 2 :(得分:0)

我相信你会通过从字符串连接切换到直接操作对象来获得你想要的东西:

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