javascript 关于 Json 的 Switch 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5174216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:15:53  来源:igfitidea点击:

Switch Statement on Json?

javascriptjqueryjson

提问by chobo2

I am wondering how do I make a switch statement in json?

我想知道如何在 json 中创建 switch 语句?

{"Errors":{"key1":"afkafk"},"IsValid":false,"SuccessMessage":""}

I tried

我试过

switch(response)
{
   case response.Errors.key1:
    alert('test');
   default: 
}

But it seems to ignore my first case.

但它似乎忽略了我的第一个案例。

Edit

编辑

// if undefined then go to next if statement - I am not sure if I can do something 
// like !=== null
if (response.Errors.key1)
            {
               // display value of key1 
            }
else if(response.Errors.Key2)
{
   // display value of key2 differently
}

So that is what I am trying to do just with a switch statement.

所以这就是我试图用 switch 语句做的事情。

回答by Darin Dimitrov

This would be the correct syntax:

这将是正确的语法:

switch(response.Errors.key1)
{
    case 'afkafk':
        alert('test');
        break;
    default:
        alert('default');
}

But I suspect that in your case the following structure would be more adapted:

但我怀疑在您的情况下,以下结构会更适合:

{ Errors: { key: 'key1', message: 'afkafk' }, IsValid: false, SuccessMessage: '' }

because it would allow you to switch on the key:

因为它可以让你打开钥匙:

switch(response.Errors.key)
{
    case 'key1':
        alert(response.Errors.message);
        break;
    default:
        alert('default');
}

回答by JaredPar

It sounds like you want to switch on the value key1instead of the name key1.

听起来您想打开 valuekey1而不是 name key1

switch (response.Errors.key1) {
  case 'afkafk':
   ...
}

回答by Melv

I'm not entirely sure what you're trying to achieve. Are you trying to switch based on the value of key1? Switch statements need to be able to match the variable you pass to the switch statement with the value of a case statement, so the following would work, although I'm not sure if it's what you're after:

我不完全确定你想要实现什么。您是否尝试根据 key1 的值进行切换?Switch 语句需要能够将传递给 switch 语句的变量与 case 语句的值相匹配,因此以下方法可以工作,但我不确定它是否是您所追求的:

switch (response.Errors.key1) {
  case 'afkafk': //do something
  break;
}