Javascript 如何从switch语句中获取返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6612541/
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-08-23 22:28:47  来源:igfitidea点击:

How to get return value from switch statement?

javascript

提问by foobar

In chrome's console, when I type:

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

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

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

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

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

It throws a syntax error "Unexpected Token switch"

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

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

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

回答by helloandre

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 actuallyreturning something.

那是因为当您将其放入 Chrome 控制台时,您将其短路。它只是打印“OK”,因为它达到了默认情况,实际上并没有返回任何东西。

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

如果你想返回一些东西,把它放在一个函数中,然后在默认情况下返回“OK”。

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

var a = switchResult(3);

回答by gaby de wilde

Perhaps interesting to note that you dont need the clutter of ;break;statements if you wrap it in a function. (as described by heloandre)

也许有趣的是,;break;如果将它包装在函数中,则不需要杂乱的语句。(如heloandre所述)

function switchResult(a){   
    switch(a){   
        case 1: return "FOO";
        case 2: return "BAR";
        case 3: return "FOOBAR";
        default: return "OK";      
    }
}
var a = switchResult(3);

回答by zarvax

ES6 lets you do this using an immediately-invoked lambda:

ES6 允许您使用立即调用的 lambda 来执行此操作:

const a = (() => {
  switch(3) {
    default: return "OK";
  }
})();

回答by NickersF

I recently had to test if switch statements can return values. I was pretty sure they could and implemented a quick terse function to test it in the FF and Chrome console.

我最近不得不测试 switch 语句是否可以返回值。我很确定他们可以并实现了一个快速简洁的功能来在 FF 和 Chrome 控制台中测试它。

function switchController(setFlag) {
  switch (setFlag) {
    case true:   return setFlag;
    case false:  return setFlag;
  }
}

console.log(switchController(true));
console.log(switchController(false));

You should get output in the console of:

您应该在控制台中获得以下输出:

true
false

You can view return values using console.log()

您可以使用查看返回值 console.log()

回答by Guffa

No, the switchdoesn't have a return value. What you see in the console is the return value of the statement inside the switchcontaining only a string literal value.

不,switch没有返回值。您在控制台中看到的是switch仅包含字符串文字值的语句的返回值。

A statement can have a return value. An assignment for example has the assigned value as return value, and post-incrementing a value returns the result after incrementing:

语句可以有返回值。例如,赋值将分配的值作为返回值,后递增值返回递增后的结果:

> a = 42;
42
> a++;
43

A statement containing just a value will have that value as return value:

只包含一个值的语句会将该值作为返回值:

> 42;
42
> "OK";
"OK"

A statement like that is however only useful in the console, for example for showing the value of a variable. In code it won't accomplish anything.

然而,这样的语句仅在控制台中有用,例如用于显示变量的值。在代码中它不会完成任何事情。

回答by Daniel A. White

Chrome is just showing you the last value evaluated. There is no output from a switch. Just use a variable.

Chrome 只是向您显示评估的最后一个值。a 没有输出switch。只需使用一个变量。

var a; 

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

回答by Moritz

What you are seeing in the chrome dev tools is the completion valueof the switch statement. Basically the value of the last evaluated expression (but not quite, e.g. the completion value of var a = 42is not 42). The completion value is a construct in ECAMScript that is usually hidden from the programmer. Though, it also comes up as the return value of eval().

您在 chrome 开发工具中看到的是 switch 语句的完成值。基本上是最后一个评估表达式的值(但不完全是,例如的完成值var a = 42不是 42)。完成值是 ECAMScript 中的一个构造,通常对程序员隐藏。不过,它也作为 的返回值出现eval()

The grammar for variable assignments expects an expression on its right-hand side so using a switch statement is that place is a syntax error:

变量赋值的语法期望在其右侧有一个表达式,因此使用 switch 语句是该位置是一个语法错误:

"var" <name> "=" <expression> 

Basically the difference between statements and expressions is that expressions compute a value while statements do not. Function calls, arithmetic, and literals are all expressions for example. "If" and "switch" statementsare not.

基本上语句和表达式之间的区别在于表达式计算一个值而语句不计算。例如,函数调用、算术和文字都是表达式。“If”和“switch”语句不是。

There is no way to capture the completion value of any statement expects perhaps wrapping it in an eval call:

无法捕获任何期望将其包装在 eval 调用中的语句的完成值:

var a = eval('switch (3) { default: "OK" }')
console.log(a) // => "OK"

But using eval for this would not be a good idea.

但是为此使用 eval不是一个好主意

Unfortunately, there is no great way to archive what you want to do. Like other answers mentioned, you could wrap the switch in a function (or IIFE) and use returnstatements to get the value out:

不幸的是,没有什么好方法可以归档您想做的事情。像提到的其他答案一样,您可以将开关包装在函数(或IIFE)中并使用return语句来获取值:

const a = (() => {
  switch(3) { default: return "OK"; }
})();

You might find this not to be an ideal solution and you are not the only one having this issue with JavaScript.

您可能会发现这不是一个理想的解决方案,而且您并不是唯一一个遇到 JavaScript 问题的人。

It is my understanding that this is one of the motivations of the pattern-matchingECAMScript proposal. But the proposal is in Stage 1 and not yet ready for production use.

我的理解是,这是模式匹配ECAMScript 提案的动机之一。但该提案处于第 1 阶段,尚未准备好用于生产。

Furthermore, you might want to write your code in a way that does not need switchstatements at all. A while ago I came across the following pattern that is apparently common in Lua but I never saw it used in JavaScript:

此外,您可能希望以一种根本不需要switch语句的方式编写代码。不久前,我遇到了以下模式,它在 Lua 中显然很常见,但我从未在 JavaScript 中使用过它:

Instead of using a switch statement you could put all your cases as properties in a JavaScript object and use functions as values instead of the logic in the individual caseblocks. This might look something like this:

您可以将所有 case 作为属性放在 JavaScript 对象中,并使用函数作为值而不是单个case块中的逻辑,而不是使用 switch 语句。这可能看起来像这样:

const cases = {
  "FOO": () => 1,
  "BAR": () => 2,
  "BAR": () => 3,
};


const value = "FOO";
const result = cases[value]();
console.log(result); // => 1

Instead of this:

取而代之的是:

let result;
switch (value) {
    case "FOO":
        result = 1;
        break;
    case "BAR":
        result = 2;
        break;
    case "BAR":
        result = 3;
        break;
}

If you need non-string cases you might want to use a Map.

如果您需要非字符串情况,您可能需要使用Map