我想创建一个计算采取起始号,结束数和步数由步长值,以显示所有甚至开始和结束计数之间的数字。
似乎是坏了我的循环的逻辑,因为它不会停止和崩溃。的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