The switch statement is a string vs int

I have this javascript line in an event handler:

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

which I then use in the 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 apply this to an int?

Or is there a way to get the value as int, for example using jQuery ()?

Or do I just need to use strings in a switch statement?

+4
source share
3 answers

Or is there a way to get the value as int, for example using jQuery ()?

Of course, this is almost always a function provided in a language or environment. There are four ways in JavaScript:

  • parseInt . value = parseInt(value, 10) (, 10, , ). , parseInt , , - . , parseInt("1blah", 10) - 1.

  • parseFloat (, 1.2), . 10.

  • Number: value = Number(value). , , , , : - , 0x, ( 16) , 0, ( 8). .

  • , ; - +. : value = +value. value = Number(value). , , Number , .

: 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
+6

+value, +

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

Try it. The parseInt()function parses the string and returns an integer.

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

Source: https://habr.com/ru/post/1524827/


All Articles