简体   繁体   English

如何使用带有switch语句的JavaScript + =

[英]How to use the JavaScript += with a switch statement

I have the following: 我有以下内容:

let buttonClass = '';
buttonClass += link ? ' button-link ' : '';

I would like to add: 我想补充一下:

let buttonClass = '';
buttonClass += link ? ' button-link ' : '';
buttonClass += 
  (return switch(textAlign) {
        case "right":
          "ta-r"
          break;
        case "left":
          "ta-l"
          break;
        default:
          "ta-c"
})

The above is erring... How can I use += with a switch statement as seen above? 以上是犯了错误...如何使用+=和switch语句如上所示?

You won't be able to do that. 你将无法做到这一点。

An alternative is using IIFE (Immediately Invoked Function Expression) 另一种方法是使用IIFE(立即调用函数表达式)

 var textAlign = 'right'; var buttonClass = "class-name-" buttonClass += (function() { switch (textAlign) { case "right": return "ta-r" case "left": return "ta-l" default: return "ta-c" } })(); console.log(buttonClass); 

I'd use an object: 我用了一个对象:

buttonClass += {
  "right": "ta-r",
  "left": "ta-l",
}[textAlign] || "ta-c";

That instantiates a throw-away object (which you could of course replace with a more permanent object) and looks up the current textAlign value. 这实例化一个抛弃对象(当然你可以用一个更永久的对象替换它)并查找当前的textAlign值。 If no entry is found, the [ ] expression will return undefined so the || 如果没有找到条目, [ ]表达式将返回undefined因此|| provides the default. 提供默认值。

By itself, switch does not return a value that you can insert into a larger expression. switch本身不返回可以插入较大表达式的值。 It branches into one set of code that is executed. 它分支成一组执行的代码。 A simple way to make this work is to set the value of a variable via the switch : 一个简单的方法是通过switch设置变量的值:

let buttonClass = '';
buttonClass += link ? ' button-link ' : '';
var result = null; // Answer will wind up here
switch(textAlign) {
        case "right":
          result = "ta-r";
          break;
        case "left":
          result = "ta-l";
          break;
        default:
          result = "ta-c";
}

// Whatever the switch set the result to, use it here:
textAlign += result;

As others have pointed out as well, you can certainly wrap switch with a function and have the function return a value based on the outcome of the switch . 正如其他人已经指出的那样,你当然可以用一个function来包装switch ,并让函数根据switch的结果返回一个值。

function wrapSwitch(tAlign){
  switch(tAlign){
        case "right":
          return "ta-r";
        case "left":
          return "ta-l";
        default:
          return "ta-c";
  }
}

textAlign += wrapSwitch(textAlign);
let buttonClass = '';
buttonClass += link ? ' button-link ' : '';

const switchFn = (textAlign) => {
    switch(textAlign) {
        case "right":
            return "ta-r";

        case "left":
            return "ta-l";

        default:
            return "ta-c";
    }
}

textAlign += switchFn(textAlign)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM