$(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"
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.
No you can't.
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 .
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:
If you change your switch to:
switch (String(this)) {
...that will turn it back into a primitive, whereupon your switch
works.
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) { // ... } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With