nick
nick

Reputation: 193

Mapping string of numbers to ints returning NaN

I have a simple program where it gets users grades and calculates their weighted grades. My function takes a string of grades and returns an array of integers, but keeps returning Nan. Here is my function:

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";
  }  
}

So if I call it with getUserScores("test") it'd grab testGrades value which is "96, 92, 94" and returns NaN instead of [96, 92, 94]? What am I doing wrong here?

Upvotes: 1

Views: 77

Answers (2)

Kevin Ji
Kevin Ji

Reputation: 10499

Alternatively, just remove the switch statement altogether:

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;  
}

To ensure that the code wouldn't break when an element didn't exist, I return null when getElementById can't find anything.

Upvotes: 2

jperelli
jperelli

Reputation: 7207

You need to add a break in each case, and also return category

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;
}

Also, make sure that you are grabbing the value that you need, that the selector is working right with:

category = document.getElementById("testGrades").value;
// add a console.log to test it
console.log(category);

Upvotes: 0

Related Questions