我的for循环没有被执行

时间:2017-08-28 11:34:05

标签: angular ionic2

我有一个条件里面我有一个循环当我运行代码我能够通过条件,但在我的条件我有一个循环不会被执行。

这一行上面的构造函数

 currentDate = new Date();

班级内的这一行

if (form.value.packType == "Per Week") {
            console.log("I could able to see this console");
            for (var a = this.currentDate.getDate(); a < 8; a++) {
                console.log("I could not see this console",a)
            }
    }

在我的控制台中,我能够看到&#34;每周&#34;值,但我无法在我的日志中看到控制台。

有人可以帮助我。

3 个答案:

答案 0 :(得分:0)

因为今天的日期是28(例如)所以a = 28并且您的条件类似a < 8所以条件变为false并且它将从循环中退出而不执行单个循环。

答案 1 :(得分:0)

如果在控制台中记录currentDate.getDate(),您将看到它的值为28.因为这大于8,所以不执行循环。

console.log(currentDate.getDate())

也许你应该澄清循环中的条件是什么来帮助你。

答案 2 :(得分:0)

在你的for循环中,当你这样做时:a = this.currentDate.getDate();你会得到'28',这使得循环执行条件为false而且根本不运行。

您需要的是获取当前日期,并运行7天的循环,并使用setDate()方法获取日期。这就是你应该这样做的方式:

if (form.value.packType == "Per Week") {

    // get the current day 
    let currentDateDay = this.currentDate.getDate();

    // get the next 7 dates from currectDate
    for(var a=1;a<=7;a++){
        // Get the next date
        let nextDate = new Date();
        nextDate.setDate(currentDateDay+a);
        console.log(nextDate); 
    }
}

链接到Plunker Demo

相关问题