跳到主要内容
青山指南正在为您准备页面
医疗级专业核验
透明收费 · 拒绝隐形 每天 08:00-20:00
资讯

定义一个数组,包含9个任意的整数,求该数组中奇数的个数

养老服务、照护经验与行业动态,为家庭提供实用参考。

定义一个数组,包含9个任意的整数,求该数组中奇数的个数

方法一:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <script>
            let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            let sum = 0;
            let j = 0;
            for (i = 0; i < arr.length; i++) {
                if (arr[i] % 2 == 0) {
                    sum = sum + 1;
                } else {
                    j = j + 1
                }
            }

            console.log(`偶数有: ${sum}个`)
            console.log(`奇数有: ${j}个`)
        </script>
    </body>
</html>

方法二:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <script>
            // 拓展题:定义一个数组,包含9个任意的整数,求该数组中奇数的个数,要求使用forEach方法。(考点:定义数组、forEach遍历数组、判断奇偶)
            let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            let sum = 0;
            let j = 0;
            arr.forEach(function(v,i) {
                if (v % 2 == 0) {
                    sum = sum + 1;
                } else {
                    j = j + 1;
                }
            })

            console.log(`偶数有: ${sum}个`)
            console.log(`奇数有: ${j}个`)
        </script>
    </body>
</html>
咨询顾问返回首页
分享经验

发表评论

读者交流

全部评论

0

还没有评论,欢迎留下第一条讨论。