for循环例题

例:用for循环算出2017年9月8日至2020年8月27日一共有多少天

<script>

        let year = 2017

        let month = 9

        let date = 8

        let endYear = 2020

        let endMonth = 8

        let endDate = 27

        let total = 0

        total += date

        //常用于确定次数的循环操作

        for (let i = 1; i <= month - 1; i++) {

            switch (i) {

                case 1:

                case 3:

                case 5:

                case 7:

                case 8:

                case 10:

                case 12:

                    total += 31

                    break;

                case 1:

                case 4:

                case 6:

                case 9:

                case 11:

                    total += 30

                    break;

                case 2:

                    total += 28

            }

        }

        total = 365 - total //17年剩余的天数

        //2020-8-27

        for (let i = 1; i <= endMonth - 1; i++) {

            switch (i) {

                case 1:

                case 3:

                case 5:

                case 7:

                case 8:

                case 10:

                case 12:

                    total += 31

                    break;

                case 1:

                case 4:

                case 6:

                case 9:

                case 11:

                    total += 30

                    break;

                case 2:

                    total += 29

            }

        }

        total += (endYear - year - 1) * 365

        console.log(total);

    </script>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。