Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch case as string

Tags:

javascript

$(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 an in console it return 2xdefaults. Why?

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

like image 501
kraYz Avatar asked Feb 16 '13 13:02

kraYz


People also ask

Can a switch case be a string?

Java switch case is a neat way to code for conditional flow, just like if-else conditions. Before Java 7, the only means to achieve string based conditional flow was using if-else conditions. But Java 7 has improved the switch case to support String also.

Can we use string in switch case in C?

No you can't.

How do you match a string in a switch case?

To ensure that we have a match in a case clause, we will test the original str value (that is provided to the switch statement) against the input property of a successful match . input is a static property of regular expressions that contains the original input string. When match fails it returns null .


1 Answers

The reason you're seeing this behavior is that this within the each call is a String object instance, not a string primitive. JavaScript has both. In a switch statement, the comparison with the cases is via ===, and a string instance is not === to a string primitive.

Three ways to fix it:

  1. If you change your switch to:

    switch (String(this)) { 

    ...that will turn it back into a primitive, whereupon your switch works.

  2. As VisioN points out in the comments below, use the arguments that $.each passes (each string — as a primitive — will be provided as the second argument):

    $.each(typ, function(index, value) {     switch (value) {         // ...     } }); 
  3. Use any of the alternatives discussed in this other answer (one of which is a nice simple for loop).


Side note: You're falling prey to The Horror of Implicit Globals by not declaring your typ variable.

like image 53
T.J. Crowder Avatar answered Sep 28 '22 04:09

T.J. Crowder