switch statement - string vs int

I have this line of javascript in an event handler:

var value =  event.currentTarget.value; //example: 9

which I then use in a switch statement.

switch (value) {

    case 9:
        return 12;
    case 12:
        return 9;
}

The problem is that "value" is a string instead of an int.

Should I just cast this to an int?

Or is there a way to get the value as an int, like say with jQuery()?

Or should I just use strings in the switch statement?

Answers


Or is there a way to get the value as an int, like say with jQuery()?

Of course, this is almost always a feature provided in a language or environment. In JavaScript, there are four ways:

  1. parseInt will parse the string as a whole number. value = parseInt(value, 10) will parse it as decimal (e.g., base 10, the number system most of us use). Note that parseInt will parse the number it finds at the beginning of the string, ignoring anything after it. So parseInt("1blah", 10) is 1.

  2. parseFloat will parse the string as a potentially-fractional number (like 1.2), if the string contains a decimal point. It always works in base 10.

  3. The Number function: value = Number(value). That expects the entire string to be a number, and figures out what number base it is by looking at the string: The default is decimal, but if it starts with 0x it's parsed as hexadecimal (base 16), and on some engines in loose mode if it starts with 0 it's parsed as octal (base 8). There's no way to force it to use a particular number base.

  4. Force the engine to implicitly convert it by applying a math operator to it; the usual one is +. So: value = +value. That does the same thing value = Number(value) does. Oddly, it tends to be slower than Number on some engines, but not enough to matter.

Examples: Live Copy

parseInt("15", 10):  15
parseFloat("15"):    15
Number("15"):        15
+"15":               15

parseInt("1.4", 10): 1
parseFloat("1.4"):   1.4
Number("1.4"):       1.4
+"1.4":              1.4

parseInt("10 nifty things", 10): 10
parseFloat("10 nifty things"):   10
Number("10 nifty things"):       NaN
+"10 nifty things":              NaN

Simple use +value, Notice + in front of a variable with converts the variable to a number

switch (+value) {
    case 9:
        return 12;
    case 12:
        return 9;
}

Try this one. parseInt() function does parse a string and returns an integer.

var value =  parseInt(event.currentTarget.value, 10); 

Need Your Help

Virtual function for printing generic linear linked list

c# generics singly-linked-list

I have an assignment to implement a linear linked list using generics in C# console application.