javascript - 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()但我到目前为止看到的输出是未定义的,或者根本没有显示输出。
解决方案
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>
推荐阅读
- react-native - 让 TapGestureHandler 在 React Native 中表现得像 TouchableOpacity?
- spring - 创建名为“webSecurityConfig”的 bean 时出错
- reactjs - 组件在 redux 状态更新后不重新渲染 - Redux Hooks - useSelector()
- azure-devops - 无法配置新代理:无法创建 CoreCLR,HRESULT:0x80004005
- java - LWJGL3 - 不能渲染三角形但可以清除颜色
- talend - Talend 中子作业执行的部分依赖关系
- python - 如何将常量从 python 文件加载到 bash 脚本?
- regex - 如何基于带有通配符的正则表达式在 nginx 位置之间设置路由
- python - 如何使用 Qt 和 Qurl 上的 Windows 路径解决此问题?
- javascript - react.js中根据url参数显示或隐藏元素