3
목표는 매트릭스의 각 요소에 동적으로 선택된 변환 집합을 효율적으로 적용하는 것입니다. 선택한 함수를 배열에 저장 한 다음 행렬을 통해 단일 패스에 각 함수를 적용합니다.자바 스크립트에서 동적으로 생성 된 함수 이름을 적용하는 방법
제 질문은 함수 배열에 추가하는 함수의 이름을 어떻게 동적으로 만들 수 있습니까?
이 내 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);
}
내가 원하는 것을 추가했습니다. 기본적으로이 이름을 String.prototype에 연결하면 다음과 같습니다. var lowerUpperFunction = String.prototype [ 'to'+ whichCase + 'Case']; 이것을 다음과 같이 호출하십시오. var str = lowerUpperFunction.call ("xyz"); – nixkuroi
고맙습니다, nixkuroi. 그게 내가하려고했던 것 같아. 늦었 어. 내일 내가 그걸 가지고 놀거야. 도와 줘서 고마워! –