首页 > 代码库 > js-循环-计算1+2+3 ... +98+99+100的值

js-循环-计算1+2+3 ... +98+99+100的值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    //    计算1+2+3 ... +98+99+100的值

    //1 .for循环
    //    前测试循环
    function sum_all() {
        var result = 0;
        for (var i = 0; i <= 100; i++) {
            result += i;
        }
        return result
    }

    var s = sum_all();

    alert(s);

    //2. while()循环
    //    前测试循环
    function sum_all2() {
        var result2 = 0;
        var i = 0;
        while (i <= 100) {
            i++;
            result2 += i;
        }
        return result2
    }

    alert(sum_all2());


    //    do-while语句
    //    后测试循环语句
    function sum_all3() {
        var result3 = 0;
        var i = 0;
        do {
            i++;
            result3 += i;
        }
        while (i <= 100);

        return result3
    }

    alert(sum_all3())
</script>
</body>
</html>

 

js-循环-计算1+2+3 ... +98+99+100的值