简体   繁体   English

在Javascript中,如何应用动态创建的函数名称

[英]In Javascript, how to apply a dynamically created function name

My goal is to efficiently apply a dynamically chosen set of transforms to each element of a matrix. 我的目标是有效地将动态选择的变换集应用于矩阵的每个元素。 I store the selected functions in an array, then apply each of them in a single pass thru the matrix. 我将选定的函数存储在一个数组中,然后通过矩阵一次性地应用它们。

My question is, how can I dynamically create the name of a function that I add to the array of functions? 我的问题是,如何动态创建我添加到函数数组的函数的名称?

This fiddle contains my attempt. 这个小提琴包含了我的尝试。 My question is included in the comment block. 我的问题包含在评论栏中。

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);
}

I like to declare my functions in a hash in this case, then you can call them based on the value passed in, which is the key to the hash. 在这种情况下,我喜欢在哈希中声明我的函数,然后你可以根据传入的值来调用它们,这是哈希的关键。

Updated: I've added a way to get the lower/upper function dynamically, and call it. 更新:我添加了一种动态获取下/上功能的方法,并调用它。

 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) ); 

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

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