2017-04-06 2 views
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); 
} 

답변

2

나는,이 경우 해시 내 함수를 선언하는 다음 해시의 열쇠에 전달 된 값에 기반을 호출 할 수 있습니다 좋아한다.

업데이트 : 하위/상위 함수를 동적으로 가져 오는 방법을 추가하고 호출했습니다.

+0

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

감사합니다. 이 솔루션의 효과에 대해 고맙지 만 실제로 텍스트 연결을 사용하여 실제로 함수 이름을 만드는 방법이 있는지 궁금해합니다. –

+0

내가 원하는 것을 추가했습니다. 기본적으로이 이름을 String.prototype에 연결하면 다음과 같습니다. var lowerUpperFunction = String.prototype [ 'to'+ whichCase + 'Case']; 이것을 다음과 같이 호출하십시오. var str = lowerUpperFunction.call ("xyz"); – nixkuroi

+0

고맙습니다, nixkuroi. 그게 내가하려고했던 것 같아. 늦었 어. 내일 내가 그걸 가지고 놀거야. 도와 줘서 고마워! –