【问题标题】:Execute different functions based on conditions without if statements根据条件执行不同的功能,无需 if 语句
【发布时间】:2018-09-14 10:21:53
【问题描述】:

有没有更好的方法/编码风格来在不同的条件下执行不同的功能使用 if 语句?

我一直在 JavaScript 中使用以下方式进行编码:(例如,不同条件下的函数可能使用 API 中的不同获取方法)

if(answer == 'a'){
  foo()

if(answer == 'b'){
  bar()

if(answer == 'c'){
  bar_2()

if(answer == 'd'){
  foo_3()

我曾想过使用eval(),但这是一个好方法吗?例如,创建一个对象由作为条件的键和作为属性的函数名组成。

conditions:{
  a: 'foo',
  b: 'bar',
  c: 'foo_2',
  d: 'bar_2',
}

然后像eval(this.conditions[a]) 一样运行它

但我也听说使用eval 很难进行测试。

【问题讨论】:

  • 不要存储带有函数名和eval的字符串。只需存储函数本身,然后调用它们!

标签: javascript performance coding-style


【解决方案1】:

是的,您可以使用该函数构建您的条件对象并调用它们:

function foo(){...}
function bar(){...}

var conditions : {
    'a': foo,
    'b': bar,
}

conditions[answer]()

注意:尽量不要使用eval,如果你不知道自己在做什么,会有安全风险

【讨论】:

    【解决方案2】:

    您使用 key 来指向函数标识符。你最好用key来指向函数:

    conditions:{
      a: () => {
        // body of foo
      },
      b: () => {
        // body of bar
      },
      c: () => {
        // body of foo_2
      },
      d: () => {
        // body of bar_2
      }
    }
    
    conditions[ your_key ]();
    

    【讨论】:

      【解决方案3】:

      您可以定义对函数的引用或在每个条件下执行

      const doSomething = (args) => {
          // do something
      }
      const doSomethingElse = (args) => {
          // do something else
      }
      
      const conditions = {
          a: doSomething,
          b: doSomethingElse
      };
      
      // and then
      const result = conditions[answer](params);
      

      甚至是函数引用列表

      const conditions = {
          a: [
              doSomething,
          ],
          b: [
              doSomething,
              doSomethingElse
          ]
      };
      // and then
      const results = conditions[ answer ].map(method => method());
      

      【讨论】:

        【解决方案4】:

        你可以像这样创建函数:

        this['some answer'] = function() {...}
        

        然后这样称呼它

        this[answer]()
        

        【讨论】:

          猜你喜欢
          • 2021-02-17
          • 2011-10-19
          • 1970-01-01
          • 2016-11-24
          • 1970-01-01
          • 2019-02-26
          • 2023-01-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多