【问题标题】:Javascript/Node.js Can I use Hashmap to Selectively Execute FunctionsJavascript/Node.js 我可以使用 Hashmap 来选择性地执行函数吗
【发布时间】:2013-09-12 10:26:07
【问题描述】:

我的应用程序有一个首选项列表,存储在一个 JSON 文件 (preferences.json) 中。我有一个相应功能的列表,我想根据偏好有选择地使用它们。每个函数的结果将被添加到报告中。

preferences.json 看起来像这样:

{
    "getTemperature": true;
    "getHumidity": false;
    "getPrecipitation": true
}

这些函数在我正在导入的模块中(functions.js)。他们是这样的:

var getTemperature = function(){
  //retrieve temperature;
  //append temperature to file;
}

var getHumidity = function(){
  //retrieve humidity;
  //append humidity to file;
}

var getPrecipitation = function() {
  //retrieve precipitation;
  //append precipitation to file;
}

到目前为止,我已经尝试过,显然没有用

var prefs = require('./preferences.json');
var funcs = require('./functions.js');

for (key in prefs){
  if(prefs[key]) {
    funcs.key(); // <- Doesn't work, b/c 'key()' isn't a function. But you get the idea.
  }
}

如果你知道如何做到这一点,请告诉我。

我还没有尝试过的一个想法(它需要重写大量代码)是将函数与首选项虚拟变量一起嵌套在伪类中。然后,我将使用首选项文件创建伪类的实例。我的想法是,伪类实例将具有完整的首选项,我可以将选择性执行硬编码到每个函数中(即 if(myInstance.tempBool){myInstance.getTemperature()} )。不过我宁愿迭代,因为还有更多功能,我可能会在未来添加更多功能。

有什么想法吗?

【问题讨论】:

标签: javascript json node.js hashmap


【解决方案1】:

根据我在上面评论中的链接调整答案并将其应用于您的情况:

您的 functions.js 文件将包含以下内容:

exports.weatherFunctions = {

    var getTemperature = function(){
      //retrieve temperature;
      //append temperature to file;
    }

    var getHumidity = function(){
      //retrieve humidity;
      //append humidity to file;
    }

    var getPrecipitation = function() {
      //retrieve precipitation;
      //append precipitation to file;
    }

}

在您的文件中要求您在上面尝试过:

var prefs = require('./preferences.json');
var funcs = require('./functions.js')

从这里你可以随意循环。

for (key in prefs){
  if(prefs[key]) {
    funcs.weatherFunctions[key](); 
  }
}

【讨论】:

    【解决方案2】:

    您可以创建一个对象,其中函数的名称作为键,函数的名称作为值:

    funcs = {
      getTemperature: function(){
        //retrieve temperature;
        //append temperature to file;
      }
    
      getHumidity: function(){
        //retrieve humidity;
        //append humidity to file;
      }
    
      getPrecipitation: function() {
        //retrieve precipitation;
        //append precipitation to file;
      }
    }
    

    如果你想把它们放在一个单独的文件中并与var funcs = require('./functions.js');一起使用,你可以放:

    module.exports = funcs
    

    现在您的主文件应该几乎可以按原样工作了。您需要将funcs.key(); 行更改为funcs[key]();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      相关资源
      最近更新 更多