Switch housing as a string

$(document).ready(function(){

    createForm("text,password",".content");  

});

function createForm(types,object){

    typ = types.split(',');

    //var source = "";

    $.each(typ,function(){

        switch(this){

            case "text":
            console.log('text');break;
            default: console.log('default');break;
        }


    });
    //$(object).html(source);
}

I have this code, and in the console it returns 2xdefaults. Why?

I am trying to return the input for each type as text or password, but my switch does not recognize "typ"

+5
source share
4 answers

The reason you see this behavior is because thisin the call it eachis an instance of the object String, not a string primitive. JavaScript has both. In the expression, switchcomparison with cases occurs through ===, and the string instance is not ===for the string primitive.

Three ways to fix it:

  • If you change your switch to:

    switch (String(this)) {
    

    ... which will return it to the primitive, after which yours switchwill work.

  • VisioN , , $.each ( — &mdash, ):

    $.each(typ, function(index, value) {
        switch (value) {
            // ...
        }
    });
    
  • , ( for).


: , typ.

+8

jQuery , jQuery T.J. .

, for -loop. :

var types = "text,password".split(",");
for (var i = 0; i < types.length; i++) {
    switch(types[i]){
        case "text":
            console.log('text');
        break;
        default: 
            console.log('default');
        break;
    }
}
+3

$.each. :

$.each( typ, function( key, value ) {
    switch(value){

       case "text":
            console.log('text');break;
       default:
            console.log('default');break;
    }
});
+2
source

Try using switch(String(this))instead switch(this). And of course, initialize your variables.

0
source

All Articles