我必须创建一个函数,接受用户输入的一系列学生的姓名和数字等级。我点击添加按钮将数据添加到数组。现在我想显示名称和等级,但将数字等级转换为字母等级。我有一切工作,除了要改变的数字。我的代码将向您显示我使用if循环和if else语句,但它似乎没有抓取数据。这是我的代码:
html>
<head>
<meta charset=utf-8 />
<title>Compute the average marks and grade</title>
<link rel="stylesheet" type="text/css" href="Looping.css">
<meta REQUIREMENT=
"Using JavaScript, create a function that will accept user
input for the name and grade for a series of students. As
input is given, store information (name and grade) in an
array. Click the 'Add' button after entering each student's
data. Click the 'Display' button to display the name and grade
for each student and, then, the average for all grades.">
<script>
var userName, userAge;
var nameData = [];
var gradeData = [];
function addToArray() {
txtName = document.getElementById("txtName").value;
txtGrade = parseInt(document.getElementById("txtGrade").value);
alert(txtName + " " + txtGrade);
nameData.push(txtName);
gradeData.push(txtGrade);
document.getElementById("txtName").focus();
document.getElementById("txtName").value = "";
document.getElementById("txtGrade").value = "";
}
function displayContent() {
for (var i = 0; i < nameData.length; i++) {
//document.write("" + nameData[i] + " ," + gradeData[i] + "<br>");
if (gradeData >= 90) {
document.write( "" + nameData[i] + "A");
}
else if (gradeData >= 80) {
document.write("" + nameData[i] + "B");
}
else if (gradeData >= 70) {
document.write("" + nameData[i] + "C");
}
else if (gradeData >= 60) {
document.write("" + nameData[i] + "D");
}
else {
document.write("" + nameData[i] + "F");
}
}
}
</script>
</head>
<body onload="showPrompt()">
<h2>Compute Average Grades</h2>
<div id="content">
<p>Enter names and grades into a tow-dimensional array (and array of two arrays)
using text boxes for input and two buttons; one to "Add" input to the arrays
and one to calculate the average grade and "Display" the information in the arrays.
</p>
<p>
<label for="txtName">Student Name:</label>
<input type="text" id="txtName" value="">
<br><br>
<label for="txtGrade">Grade:</label>
<input type="text" id="txtGrade" value="">
<br><br clear: left>
</p>
<div style="text-align:center">
<input type="button" class = "btnClass" value="Add" onclick="addToArray()">
<input type="button" class = "btnClass" value="Display" onclick="displayContent()">
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
您在所有gradeData
语句中都缺少if
的索引引用。例如,第一个说:
if (gradeData >= 90) {
。 。 。它应该说:
if (gradeData[i] >= 90) {
答案 1 :(得分:0)
你的displayContent函数应该是这样的:
function displayContent() {
for (var i = 0; i < nameData.length; i++) {
//document.write("" + nameData[i] + " ," + gradeData[i] + "<br>");
if (gradeData[i] >= 90) {
document.write( "" + nameData[i] + "A");
}
else if (gradeData[i]>= 80) {
document.write("" + nameData[i] + "B");
}
else if (gradeData[i]>= 70) {
document.write("" + nameData[i] + "C");
}
else if (gradeData[i]>= 60) {
document.write("" + nameData[i] + "D");
}
else {
document.write("" + nameData[i] + "F");
}
}
}