【问题标题】:Call a function according to its string name [duplicate]根据其字符串名称调用函数[重复]
【发布时间】:2022-02-08 02:58:27
【问题描述】:

我有一个非常重复的代码,它根据数组字符串的名称执行一个或另一个函数。

我给出一个我能做到的代码示例。

// I use underscore in NodeJS

_.each(refresh, (value, key) => {

    if(key === 'station') {

        station.add({ id: value });

    } else if(key === 'concentrator') {

        concentrator.add({ id: value });
        
    } else if....
});

可以根据你的字符串运行函数,避免用 IF 等检查太多

[key].add({ id: value });

我在网上看了几个小时关于通话、申请等的使用;但我不明白它是如何运作的,可能是因为我对 Javascript 的了解不高。

谢谢!

【问题讨论】:

  • const myObj = { station : whatEverYouDo }; myObj[key].add()

标签: javascript jquery node.js javascript-objects


【解决方案1】:

在对象上创建匿名函数是最好的方法。因为你可以使用key来调用方法。

以下是代码笔中的示例: https://codepen.io/liam-hamblin/pen/KKyapNP

上面的代码接受了用于分配功能的键,不需要任何检查。但是,在调用之前检查密钥是否存在始终是最好的方法。

const operations = {};

operations.add = (obj) => {
  document.write("add - ");
  document.write(JSON.stringify(obj));
}

operations.subtract = (obj) => {
  document.write("subtract - ");
  document.write(JSON.stringify(obj));
}

const input = prompt("Enter Function Name, type either subtract or add");

if (operations[input]) {
  operations[input]({id:1});
} else {
  document.write("no matching method")
}

【讨论】:

  • 这是不同的功能。您使用从字符串调用的方法,我需要从字符串运行 add 方法。
猜你喜欢
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2023-03-09
  • 2014-11-20
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多