【问题标题】:In Javascript, how to apply a dynamically created function name在 Javascript 中,如何应用动态创建的函数名称
【发布时间】:2017-04-06 00:08:28
【问题描述】:

我的目标是有效地将一组动态选择的变换应用于矩阵的每个元素。我将选定的函数存储在一个数组中,然后将它们中的每一个应用到矩阵中。

我的问题是,如何动态创建添加到函数数组中的函数名称?

这个fiddle 包含我的尝试。我的问题包含在评论块中。

function dynam () {

  var prepend = 'before - ';
  var append = ' - after';
  var whichCase = 'Upper';

  var functionsToApply = [];
  var matrix = [
                   ['aBc', 'DeF'],
                   ['ghi', 'JKL'],
               ];

  var out = 'Initial: ' + matrix.join(' | ');
  document.getElementById('output').innerHTML =  out + '\n';
  console.log(out);

  // Set up transforms
  if (whichCase == 'Lower') {
    functionsToApply.push(function(v) {return v.toLowerCase();});
  } else if (whichCase == 'Upper'){
    functionsToApply.push(function(v) {return v.toUpperCase();});
  }

// How can the function be defined dynamically?
// Perhaps something like:
//  if(['Lower','Upper'].indexOf(whichCase) != -1) {
//    functionsToApply.push(function(v) {'return v.to' + which + 'Case();'});
//  }

  if (prepend && prepend.length > 0 && prepend != 'none') {
    functionsToApply.push(function(v) {return prepend + v;});
  }
  if (append && append.length > 0 && append != 'none') {
    functionsToApply.push(function(v) {return v + append;});
  }

// Apply all of the transforms to each of the elements of the matrix
  matrix = matrix.map(function(row){
    return row.map(function(val) {
      for (var fn = 0; fn < functionsToApply.length; fn++) {
        val = functionsToApply[fn](val);  
      }
      return val;
    })
  }); 

  out = 'Final: ' + matrix.join(' | ');
  document.getElementById('output').innerHTML +=  out + '\n';
  console.log(out);
}

【问题讨论】:

    标签: javascript dynamic-function


    【解决方案1】:

    在这种情况下,我喜欢在哈希中声明我的函数,然后您可以根据传入的值调用它们,这是哈希的关键。

    更新:我添加了一种动态获取下/上函数并调用它的方法。

    function dynam(whichCase, prepend, append, matrix) {
    
     var functionHash = {
      "Lower" : function(v) {return v.toLowerCase();},
      "Upper" : function(v) {return v.toUpperCase();},
      "Prepend" : function(v) {return prepend + v;},
      "Append": function(v) {return v + append;}
     }
    
    // to actually get the case function based on the word passed in, 
    // you can do it this way.
    
     var lowerUpperFunction = String.prototype['to' + whichCase + 'Case'];
     var str = lowerUpperFunction.call("xyz");
     console.log(str);
    
      var functionsToApply = [];
      
      var out = 'Initial: ' + matrix.join(' | ');
      console.log(out);
     
     // see how we just take the whichCase and make that a call to the hash?
     functionsToApply.push(functionHash[whichCase]);
    
    if (prepend && prepend.length > 0 && prepend != 'none') {
        functionsToApply.push(functionHash["Prepend"]);
      }
    
    if (append && append.length > 0 && append != 'none') {
        functionsToApply.push(functionHash["Append"]);
    }
    
    // Apply all of the transforms to each of the elements of the matrix
      matrix = matrix.map(function(row){
        return row.map(function(val) {
          for (var fn = 0; fn < functionsToApply.length; fn++) {
            console.log("applying function to val" + val );
            val = functionsToApply[fn](val);  
          }
          return val;
        })
      }); 
    
      out = 'Final: ' + matrix.join(' | ');
      return out;
    }
    
    
      var p = 'before - ';
      var a = ' - after';
      var w = 'Upper';
      var m = [
                 ['aBc', 'DeF'],
                 ['ghi', 'JKL'],
             ];
      
     console.log( dynam(w, p, a, m) );

    【讨论】:

    • 谢谢。虽然我很欣赏这个解决方案的有效性,但我仍然想知道是否有一种方法可以使用文本连接来实际创建函数名称。
    • 我已经添加了你想要的东西。基本上,您可以像这样将名称连接到 String.prototype 中: var lowerUpperFunction = String.prototype['to' + whichCase + 'Case'];并这样称呼它: var str = lowerUpperFunction.call("xyz");
    • 谢谢你,nixkuroi。这看起来像我正在尝试的。现在已经很晚了,所以我明天会玩它。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多