フィールドを空白のままにすると、NaNが平均値として返されます。代わりに0を返すようにするにはどうすればよいですか?フィールドに何も入力されていない場合、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
}
感謝。私はこれのノブで、これを理解しようと何時間も苦労してきました。
複数のコードをダンプするのではなく、問題の[最小、完全、かつ検証可能な例](http://stackoverflow.com/help/mcve)を提供してください。 – JAL