问题描述
我正在尝试使用continue
来省略test3
的总平均值。
我不确定我在这里做错了什么。目标是使用所有在test3
文本框中输入的数字以外的数组。
我试图收集所有数组的总和(不包括test3
),以便在代码末尾得出平均值。
<html>
<head>
<title>Chapter 3 Activity</title>
</head>
<body>
<h1>Test score Average</h1>
<p>Insert your 5 test scores in the Boxes below</p>
<form action="">
Test 1:
<input type="text" name="test1" id=t1>
<br> Test 2:
<input type="text" name="test2" id=t2>
<br> Test 3:
<input type="text" name="test3" id=t3>
<br> Test 4:
<input type="text" name="test4" id=t4>
<br> Test 5:
<input type="text" name="test5" id=t5>
<br>
<input type="button" value="Calculate Average" onclick="calculateFunction()">
</form>
<script type="text/javascript">
function calculateFunction() {
var test1 = document.getElementById("t1").value;
var test2 = document.getElementById("t2").value;
var test3 = document.getElementById("t3").value;
var test4 = document.getElementById("t4").value;
var test5 = document.getElementById("t5").value;
var nums = [test1,test2,test3,test4,test5];
var totalSum = 0;
for (var i = 0; i < nums.length; i++) {
totalSum += parseInt(nums[i]);
if (nums[i] === test3) {
continue;
}
}
var average = totalSum / nums.length;
document.write("Test score average is " + average);
}
</script>
</body>
</html>
解决方法
快速解决方案是将if
语句移到将值添加到totalSum
的上方,就像这样:
for (var i = 0; i < nums.length; i++) {
if (nums[i] === test3){
continue;
}
totalSum += parseInt(nums[i]);
}
但是,这确实不是一个好的解决方案。例如,如果数组中的所有数字都等于5怎么办?由于我们每次都达到continue
,因此您的平均值为0。如果您的目标是在计算平均值时始终忽略数组中的第三个元素,那么这样会更好:
for (var i = 0; i < nums.length; i++) {
if (i === 2) {
continue;
}
totalSum += parseInt(nums[i]);
}
请记住要除以nums.length - 1
,因为您在计算平均值时会忽略其中一个元素。
document.getElementById("go").addEventListener("click",evt => {
// get all the inputs you want to use
let ts = document.querySelectorAll("#t1,#t2,#t4,#t5");
let total = 0;
// loop through the inputs and total them
for (let t of ts) {
// convert the value to an integer
let value = parseInt(t.value);
// check to ensure it is a number and matches with the person put in
if (!isNaN(value) && value == t.value) {
total += parseInt(t.value);
} else {
t.value = 'Ignored';
}
}
let average = total / ts.length;
document.getElementById("output").textContent = "Test score average is " + average;
});
<h1>Test Score Average</h1>
<p>Insert your 5 test scores in the boxes below</p>
Test 1: <input type="text" name="test1" id=t1><br> Test 2: <input type="text" name="test2" id=t2><br> Test 3: <input type="text" name="test3" id=t3><br> Test 4: <input type="text" name="test4" id=t4><br> Test 5: <input type="text" name="test5" id=t5><br>
<!-- Use a button rather than an input -->
<button id="go" type="button">Calculate Average</button>
<output id="output"></output>