如何在JavaScript数组中使用if语句

时间:2017-11-16 12:23:59

标签: javascript

如何在JavaScript数组中使用if语句。下面是我尝试过的代码,但它还没有工作。

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

var today = yyyy + '-' + mm + '-' + dd;


//--------------------- Begin Of Calendar Event ---------------------------//

var calendarEvents = [

  if (today == today) {

    {
      title: 'Nigeria Independence',
      url: 'http://google.com/',
      start: today
    }

  }

];

//--------------------- End Of Calendar Event ----------------------------//

3 个答案:

答案 0 :(得分:3)

首先,你的情况总是如此。所以改变它:

if ((new Date()) == today) {

此外,上述情况可能无效,因为new Date()不是today。你需要正确格式化。

其次,要在数组中包含条件,请使用三元运算符:



var today = new Date();
var calendarEvents = [
  (today == today) ? {
    title: 'Nigeria Independence',
    url: 'http://google.com/',
    start: today
  } :
  "Not Today"
];

console.log(calendarEvents);




答案 1 :(得分:1)

使用Push方法添加到数组。

var today = new Date();

    var dd = today.getDate();

    var mm = today.getMonth() + 1;

    var yyyy = today.getFullYear();

    var today = yyyy + '-' + mm + '-' + dd;


    //--------------------- Begin Of Calendar Event ---------------------------//

    var calendarEvents = [];

      if (today == today) {

        var data = {
               title: 'Nigeria Independence',
               url: 'http://google.com/',
               start: today
               }

    //add to array
    calendarEvents.push(data);
      }



    //--------------------- End Of Calendar Event ----------------------------//

答案 2 :(得分:0)

这样做,以便今天 =今天,然后创建数组

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

var today = yyyy + '-' + mm + '-' + dd;


//--------------------- Begin Of Calendar Event ---------------------------//



  if (today == today) {

   var calendarEvents = [
      {
        title: 'Nigeria Independence',
        url: 'http://google.com/',
        start: today
      } 
   ];

  }



//--------------------- End Of Calendar Event ----------------------------//