我想創建一個計算採取起始號,結束數和步數由步長值,以顯示所有甚至開始和結束計數之間的數字。
似乎是壞了我的循環的邏輯,因爲它不會停止和崩潰。的Javascript做while循環不停止
<!DOCTYPE html>
<html>
<body>
<h2>JFinding all even numbers</h2>
<p>Please input a starting number, ending number and step number:</p>
Starting Number: <input id="start">
Ending Number: <input id="end">
Step by Number: <input id="step">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var start, end, step, text;
var result = [];
// Get the value of the start number with start var
start = parseInt(document.getElementById("start").value);
// Get the value of the end number with end var
end = parseInt(document.getElementById("end").value);
// Get the value of the step number with step var
step = parseInt(document.getElementById("step").value);
console.log('start', start);
console.log('end', end);
console.log('step', step);
// If start, end, or step is Not a Number or step is not even or start is greater than end or step is greater than end or start and step are equal to end
if (isNaN(start) || isNaN(end) || isNaN(step) || step % 2 !== 0 || start > end || step > end || step === end || start === end) {
//display text for invalid input
text = "Input not valid";
//display text to html page
document.getElementById("demo").innerHTML = text;
//else create a loop to find even numbers
} else {
if(start % 2 === 0){
for(var i = start; i <= end; i += step){
result.push(i);
}
} else {
start += 1;
for(var i = start; i <= end; i += step){
result.push(i);
}
}
//sent the result to the html page
document.getElementById("demo").innerHTML = result;
}
console.log(result);
}
</script>
</body>
</html>
'sum'不會提升過去'啓動+ step'因爲'總和=開始+步驟,'你可能要爲start初始化的金額,然後把上面一行'總和+ =步;' – James