将案例切换为字符串 [英] Switch case as string

查看:60
本文介绍了将案例切换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(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);
}

我在控制台中有这个代码,它返回2xdefaults。为什么?

I have this code an in console it return 2xdefaults. Why?

我尝试将每种类型的输入作为文本或密码返回,但我的开关无法识别typ

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

推荐答案

你看到这种行为的原因是每个中的这个 call是 String 对象实例,而不是字符串原语。 JavaScript都有。在开关语句中,与案例的比较是通过 === 和字符串 instance 不是 === 到字符串原语

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.

三种方式解决它:


  1. 如果您将开关更改为:

  1. If you change your switch to:

switch (String(this)) {

...这将把它变回一个原语,然后你的开关工作。

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

As VisioN 在下面的评论中指出,使用 $。每个传递的参数(每个字符串 —作为原始 —将作为第二个参数提供):

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) {
        // ...
    }
});


  • 使用在另一个答案中讨论的替代方案(其中一个是一个很简单的 for 循环)。

  • Use any of the alternatives discussed in this other answer (one of which is a nice simple for loop).






    旁注:你'重新成为 隐含全球恐怖的的牺牲品> 未声明 typ 变量。

    这篇关于将案例切换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆