Continue语句在JavaScript for循环中无法正常工作



我正试图使用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,该怎么办?你的平均值是0,因为我们每次都会碰到continue。如果你的目标是在计算平均值时总是忽略数组中的第三个元素,那么这样做会更好:

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>

最新更新