定义一个数组,包含9个任意的整数,求该数组中奇数的个数
时间:2023-3-13 17:57 作者:小诸葛 分类: JavaScript 正在检查是否收录...
方法一:
<!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>
推荐阅读:
扫描二维码,在手机上阅读