【问题标题】:Is there a way I could iterate through dates in an array and add them to this object?有没有办法可以遍历数组中的日期并将它们添加到这个对象?
【发布时间】:2021-12-13 03:36:05
【问题描述】:

我正在使用我在网上找到的 jQuery 日历,我正在努力将日期添加到其中。 我能够遍历 API 响应并将它们推送到数组中。但是从那里我很难将它添加到日历中。

        $(function(){
          $("#calendar").simpleCalendar();
        });

        var dates = [];
        var descriptions = [];

        for(i = 0; i < result['data']['holidays'].length; i++){
          let date = result['data']['holidays'][i]['date']['iso'];
          dates.push(new Date(date));
          descriptions.push(result['data']['holidays'][i]['description']);
        }

        console.log(dates[34] + " " + descriptions[34]);
                
        $("#calendar").simpleCalendar({       
          // Events displayed
          displayEvent:true,
          // Dates of the events                  
          events: [           
            {
              startDate: dates[1],
              endDate: dates[1],
              summary: descriptions[1]
            }
          ]
        });       

我尝试将它添加到循环中并将数组键设置为“i”,但这对我不起作用。

【问题讨论】:

  • 请发布 API 数据示例。
  • console.log(result) 会给你什么?
  • 我认为你不应该有第一个 $(function(){ $("#calendar").simpleCalendar(); }); ,你也应该稍后初始化它

标签: javascript jquery arrays iterator


【解决方案1】:

在循环中填充 events 变量,并直接在 json 上使用它。

    $(function(){
      $("#calendar").simpleCalendar();
    });

    var eventsArr = [];

    for(i = 0; i < result['data']['holidays'].length; i++){
      let date = result['data']['holidays'][i]['date']['iso'];
      eventsArr.push({
          "startDate": new Date(date),
          "endDate"  : new Date(date),
          "summary"  : result['data']['holidays'][i]['description']
      });
    }

    $("#calendar").simpleCalendar({       
      // Events displayed
      displayEvent:true,
      // Dates of the events                  
      events: eventsArr
    });       

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 2022-11-22
    • 2020-12-31
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多