简体   繁体   English

使用没有开关的案例 - 这是如何工作的?

[英]Using cases without a switch - How does this work?

I saw this code on codewars - It reminded me of a switch as it has cases yet no switch.我在 codewars 上看到了这段代码——它让我想起了一个switch ,因为它有 case 但没有 switch。 How does the cases word work?案例词是如何工作的?

function basicOp(operation, value1, value2){
  let cases = {
    '+': value1 + value2,
    '-': value1 - value2,
    '*': value1 * value2,
    '/': value1 / value2
  };
  return cases[operation]
}

 function basicOp(operation, value1, value2){ let cases = { '+': value1 + value2, '-': value1 - value2, '*': value1 * value2, '/': value1 / value2 }; return cases[operation] } console.log(basicOp('+', 2, 3)) console.log(basicOp('-', 3, 1)) console.log(basicOp('*', 2, 6)) console.log(basicOp('/', 4, 2))

This has nothing to do with switch .这与switch无关。 It's an object with attributes, where the operator is passed as the key in order to get its corresponding value and perform an arithmetic operation.它是一个带有属性的 object,其中运算符作为键传递,以获取其对应的值并执行算术运算。

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

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