编写一个数字数组并只添加奇数?

javascriptobject oriented programmingprogramming更新于 2024/7/24 13:11:00

使用 JavaScript 进行奇数求和。

示例

<html>
<body>
<script>
var tot = 0;
var a = [1,45,78,9,78,40,67,76];
for(var i = 0; i<a.length;i++){
    if(a[i]%2 !== 0){
        tot += a[i]
    }
}
document.write(tot);
</script>
</body>
</html>

输出

122

解释:在上面的数组中,由于模数运算符用于查找余数,当数字除以 2 时,如果余数为 1,则其为奇数,并且编程为将数组中的所有奇数相加。


相关文章