如果輸入的最後一個數字後面有空格,程序就會中斷。如果輸入空格,我該如何阻止函數中斷?我試過$ .trim,但無法弄清楚如何讓它工作。也試過一個if/else語句如何驗證用戶輸入?
function calculate() {
var numInput = document.getElementById("qty").value;
var numArray = numInput.split(" ").map(function(t) {
return parseInt(t);
});
var minValue = Math.min.apply(null, numArray);
var maxValue = Math.max.apply(null, numArray);
var sumValue = numArray.reduce(function(previous, current) { return previous + current });
var productValue = numArray.reduce(function(previous, current) { return previous * current });
var meanValue = numArray.reduce(function(previous, current) { return previous + current/numArray.length });
document.getElementById("result").innerHTML = 'Min value is: ' + minValue + '<br>' + 'Max value is: '+ maxValue + '<br>' + 'Sum value is: ' + sumValue + '<br>' + 'Product value is: ' + productValue + '<br>' + 'Mean value is: ' + meanValue;
}
function clearAnswer(){
document.getElementById("result").innerHTML = '';
document.getElementById("qty").value = '';
}
<h1> Problem JavaScript</h1> Enter 5 numbers with spaces in between each:
<input type="text" id="qty">
<input type="button" id="go" value="Calculate" onclick="calculate()">
<button type="reset" id="reset" onclick="clearAnswer()">Clear</button>
<div id="result"></div>
哪條線斷了? – gurvinder372
如果在點擊計算後最後一個數字之後輸入了空格,則所有結果= NaN – newbieDeveloper