mattshu
mattshu

Reputation: 35

Javascript functions not returning desired result

I have a function that contains a switch statement to return a string based on an inputted integer. I've shortened it for brevity. The cases past 1 doesn't matter, as the case integer just increments and returns different string values. The setup is the same.

function idToGame(id) { switch (id) { case 1: return 'loz';break; } }

Whenever I test it using my Google Chrome console, it works fine.

idToGame(1) returns loz

So let's use the variable game as an example. Below, we are assuming the value for 'pm_game' is 1.

var game = document.getElementById('pm_game').value;

Therefore, game is set to 1.

Here's the weird part. Whenever I try to use this: (note: the value below is 1)

var game = idToGame(document.getElementById('pm_game').value);

It sets game to undefined.

Am I missing something? Why does it become undefined when it's really supposed to be loz?

Upvotes: 1

Views: 79

Answers (3)

user1636522
user1636522

Reputation:

Switches in javascript use strict type checking (===), so, 1 (Number) is considered not equal to '1' (String). Two options :

  • Try switch(parseInt(id)) to perform conversion from string to integer.
  • If you don't want to perform conversion, simply add quotes around each case values as follows : case '1'.

Additionaly, for debugging purpose, you can use typeof to print the type in the console.

Upvotes: 1

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

Switch uses the === operator. Where 1 is not equal '1'.

Just tried in the console you need to tryparse it. Below is an example.

var f = function(id) { 
   switch (parseInt(id)) 
   { 
      case 1: 
         return 'loz';
         break; 
   } 
}

with the old function: f(1) would return 'loz', but f('1') didn't.

I would prefer comparing to '1' instead of 1 - to avoid the parse. but I am not sure if this i what you want:

var f = function(id) { 
   switch (id) 
   { 
      case '1': 
         return 'loz';
         break; 
   } 
}

Upvotes: 1

dfsq
dfsq

Reputation: 193261

When you get the value of any input field, like this:

var game = document.getElementById('pm_game').value;

returned result is always a string, not a number like you expect. So in order to make it work you need to cast a string to a number. For example using parseInt:

var game = parseInt(document.getElementById('pm_game').value, 10);
// or game = + document.getElementById('pm_game').value;
// or game = Number(document.getElementById('pm_game').value);

Or move parseInt conversion into id2game function before switch.

Upvotes: 3

Related Questions