如何从switch语句获取返回值? [英] How to get return value from switch statement?

查看:192
本文介绍了如何从switch语句获取返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在chrome的控制台中,当我键入:

In chrome's console, when I type:

> switch(3){default:"OK"}
  "OK"

所以看起来switch语句具有返回值.但是当我这样做时:

So looks like the switch statement has a return value. But when I do:

> var a = switch(3){default:"OK"}

它引发语法错误意外的令牌切换"

It throws a syntax error "Unexpected Token switch"

是否可以捕获开关的return语句?

Is it possible to capture the return statement of the switch?

推荐答案

这是因为,当您将其放入Chrome控制台时,就会使其短路.它只是打印'OK',因为它达到了默认情况,而不是实际上返回任何内容.

That's because when you're putting that into the Chrome console, you're short-circuiting it. It's just printing 'OK' because it's reaching the default case, not actually returning something.

如果要返回某些内容,请将其粘贴到函数中,并在默认情况下返回确定".

If you want something returned, stick it in a function, and return the 'OK' from in the default case.

function switchResult(a){
    switch(a){
        default: 
            return "OK";
    }
}

var a = switchResult(3);

这篇关于如何从switch语句获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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