我有一个简单的程序,它可以获得用户成绩并计算他们的加权成绩。我的函数接受一系列等级并返回一个整数数组,但不断返回Nan
。这是我的功能:
function getUserScores(subject) {
var category;
switch (subject) {
case "test":
category = document.getElementById("testGrades").value;
category = category.split(',').map(function(item) {
return parseInt(item, 10);
});
case "quiz":
category = document.getElementById("quizGrades").value;
category = category.split(',').map(function(item){
return parseInt(item, 10);
});
case "homework":
category = document.getElementById("homeworkGrades").value;
category = category.split(',').map(function(item){
return parseInt(item, 10);
});
default:
return "Error: something went wrong with switch statement";
}
}
因此,如果我使用getUserScores("test")
调用它,则会抓取testGrades
"96, 92, 94"
的值并返回NaN
而不是[96, 92, 94]
?我在这里做错了什么?
答案 0 :(得分:2)
或者,只需完全删除switch
语句:
function getUserScores(subject) {
var ele = document.getElementById(subject + "Grades");
if (ele === null) {
return null;
}
var category = ele.value;
category = category.split(',').map(function(item) {
return parseInt(item, 10);
});
return category;
}
为了确保在元素不存在时代码不会中断,当null
找不到任何内容时,我会返回getElementById
。
答案 1 :(得分:0)
您需要在每种情况下添加一个中断,并返回类别
function getUserScores(subject) {
var category;
switch (subject) {
case "test":
category = document.getElementById("testGrades").value;
category = category.split(',').map(function(item) {
return parseInt(item, 10);
});
break;
case "quiz":
category = document.getElementById("quizGrades").value;
category = category.split(',').map(function(item){
return parseInt(item, 10);
});
break;
case "homework":
category = document.getElementById("homeworkGrades").value;
category = category.split(',').map(function(item){
return parseInt(item, 10);
});
break;
default:
return "Error: something went wrong with switch statement";
}
return category;
}
此外,请确保您正在抓取所需的值,选择器正在使用:
category = document.getElementById("testGrades").value;
// add a console.log to test it
console.log(category);