我是 Javascript 新手,目前正在嘗試創建一個簡單的程式,它由 2 個函陣列成,一個是計算學生成績的總數,另一個是計算成績的平均值。這是代碼
var grades = [80, 87, 94, 82, 62, 98, 81, 81, 74, 91];
var sum = 0;
function accumulatedGrades(){
for (index = 0; index<grades.length; index ){
sum = grades[index];
}
return sum / grades.length;
}
function tests(){
document.getElementById('average').innerHTML = document.write(sum/grades.length);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="js/example.js"></script>
</head>
<body>
<h2 style="color: blueviolet">Grades</h2>
<h3>This is all the grades: <br>80, 87, 94, 82, 62, 98, 81, 81, 74, and 91</h3>
<h2 style="color: blueviolet">Average</h2>
<h3 id='average'><script>tests()</script></h3>
</body>
</html>
我已經嘗試使用函式 tests()并使用document.write()但我到目前為止看到的輸出是未定義的或根本沒有顯示輸出。
uj5u.com熱心網友回復:
accumulatedGrades函式永遠不會被呼叫,所以sum是 0.
document.write并且innerHTML不能像你給出的那樣作業。document.write寫在檔案上,innerHTML是單個元素的屬性。
tests函式在 html 檔案中不可用。我已經更新了代碼,修復了accumulatedGrades正確計算總和的函式。修復了 html 并tests在 js 檔案本身中呼叫該函式。
var grades = [80, 87, 94, 82, 62, 98, 81, 81, 74, 91];
var sum = 0;
function accumulatedGrades() {
for (index = 0; index < grades.length; index ) {
sum = grades[index];
}
return sum;
}
function tests() {
document.getElementById('average').innerHTML = (accumulatedGrades()) / grades.length;
}
tests()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="js/example.js"></script>
</head>
<body>
<h2 style="color: blueviolet">Grades</h2>
<h3>This is all the grades: <br>80, 87, 94, 82, 62, 98, 81, 81, 74, and 91</h3>
<h2 style="color: blueviolet">Average</h2>
<h3 id='average'></h3>
</body>
</html>
uj5u.com熱心網友回復:
document.write() 如果在頁面加載后呼叫它可以洗掉內容。
function averageGrades(){
for (index = 0; index<grades.length; index ){
sum = grades[index];
}
return sum / grades.length;
}
document.getElementById('average').innerHTML = averageGrades();
檢查此代碼,如果需要解釋,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353792.html
標籤:javascript html 数组 功能
上一篇:分派外部組件
下一篇:如何列印內容中有鏈接的文本?
