【问题标题】:How can I get this string to convert back into the array?我怎样才能让这个字符串转换回数组?
【发布时间】:2010-07-08 22:51:24
【问题描述】:

我正在尝试使用 jMonthCalendar 将 XML 提要中的一些事件添加到日历中。在原始的 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”中的内容并没有像示例源中那样转换回数组对象。

我知道这是一个菜鸟问题,但我们将不胜感激。

【问题讨论】:

    标签: javascript arrays nested


    【解决方案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});
    

    【讨论】:

    • 哇,谢谢!我最终使用 push 而不是 append,但答案很棒。谢谢!
    【解决方案2】:

    改变你的创作循环:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-13
        • 2015-04-13
        • 1970-01-01
        • 2016-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多