如果该字段留空,则会返回NaN作为平均值。我怎样才能让它返回0呢?
这就是我的HTML文件:
<html>
<head>
<title> Average Numbers </title>
<script type="text/javascript" src="arrays.js"></script>
<script type="text/javascript">
function ShowAvg()
// Assumes: numsBox contains a sequence of numbers
// Results: displays the average of the numbers in outputDiv
{
var str, strArray, numArray;
str = document.getElementById('numsBox').value;
if ( isNan(str)){
document.getElementById('numArray').value = '0';
}
strArray = str.split(/[, \t\n]+/); // SPLIT STRING INTO AN ARRAY
numArray = ParseArray(strArray); // STORE ARRAY VALUES AS NUMS4
document.getElementById('outputDiv').innerHTML =
'The average of [' + numArray + '] is ' + Average(numArray);
}
</script>
</head>
<body>
<p>
Enter numbers: <input type="text" id="numsBox" size=40 value="">
</p>
<p>
<input type="button" value="Compute the Average" onclick="ShowAvg();">
</p>
<div id="outputDiv"></div>
</body>
</html>
这是我的javascript文件:
function Acronym(phrase)
// Assumes: phrase is a string of words, separated by whitespace
// Returns: the acronym made up of first letters from the words
{
var words, acronym, index, nextWord;
words = phrase.split(/[ \t\n]+/); // CONVERT phrase TO AN ARRAY
acronym = ''; // INITIALIZE THE acronym
index = 0; // START AT FIRST WORD
while (index < words.length) { // AS LONG AS WORDS LEFT
nextWord = words[index]; // GET NEXT WORD
acronym = acronym + nextWord.charAt(0); // ADD FIRST CHAR OF WORD
index = index + 1; // GO ON TO NEXT WORD
}
return acronym.toUpperCase(); // RETURN UPPER CASE acronym
}
function ParseArray(strArray)
// Assumes: strArray is an array of strings representing numbers
// Returns: a copy of strArray with items converted to numbers
{
var numArray, index;
numArray = [ ]; // CREATE EMPTY ARRAY TO STORE COPY
index = 0; // FOR EACH ITEM IN strArray
while (index < strArray.length) { // CONVERT TO NUMBER AND COPY
numArray[index] = parseFloat(strArray[index]);
index = index + 1;
}
return numArray; // FINALLY, RETURN THE COPY
}
function Average(numArray)
// Assumes: numArray is an array of numbers
// Returns: average of the numbers in numArray
{
var sum, index;
sum = 0; // INITIALIZE sum
index = 0; // START AT FIRST NUMBER
while (index < numArray.length) { // AS LONG AS NUMBERS LEFT
sum = sum + numArray[index]; // ADD NUMBER TO sum
index = index + 1; // GO ON TO NEXT NUMBER
}
return sum/numArray.length; // RETURN AVERAGE
}
提前感谢您提供任何帮助。我在这方面是一个菜鸟,并且一直在努力解决这个问题。
答案 0 :(得分:1)
长话短说,只需添加
value = value || 0;
表示默认值。
我遇到了以下问题
isNan()
应为isNaN()
document.getElementById('numArray').value = '0';
无效,因为它是一个按钮,而不是输入字段,请改用document.getElementById('numsBox').value = '0';
。答案 1 :(得分:0)
更长的答案:在你的js文件中,替换
return numArray;
}
与
avgNum = sum/numArray.length;
if (avgNum != avgNum) {
avgNum = 0;
}
return avgNum; // RETURN AVERAGE
}
您仍然需要更改html文件中的str NaN显示(我只是将其取出并说平均值为:因为数字仍显示在顶部)。这个工作的原因是只有这个NaN不等于它本身(这太奇怪了)。代码开启!