我的目标是有效地将一组动态选择的变换应用于矩阵的每个元素。我将选定的函数存储在一个数组中,然后通过矩阵一次应用它们中的每一个。
我的问题是,如何动态创建添加到函数数组中的函数名称?
这个小提琴包含我的尝试。我的问题包含在评论块中。
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);
}