首页 > 解决方案 > Javascript函数返回未定义的输出

问题描述

我是 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()但我到目前为止看到的输出是未定义的,或者根本没有显示输出。

标签: javascripthtmlarraysfunction

解决方案


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>


推荐阅读