0

JavaScript 関数から行の配列を取得しようとしています。特定の関数への参照が与えられた場合、各要素が関数のソースの連続する 1 行で構成される配列を返したいと思います。

例:

//the following function will be used as the input for getArrayOfLines, and each line of  functionToUse should be returned as output (represented as a string).
function functionToUse(){
    //This comment here should be included in the array of lines.
    //This is the second line that should be in the array.
}

var funcLines = getArrayOfLines(functionToUse);

// should return: 
// [ "//This comment here should be included in the array of lines.", 
//   "//This is the second line that should be in the array." ]

私がいる場所は次のとおりです。

function getArrayOfLines(theFunction){
    //return an array of lines from the function that is entered as input.
    //each line should be represented as a string
    var theString = theFunction.toString();
    // now I'll need to generate an array of lines from the string, 
    // and then return the array
}

主に、関数の各行 (一度に 1 行) を評価できるように、これを実行しようとしています。

4

1 に答える 1

0

シンプル - を使用stringtoSplit.split("\n")して行の配列を取得するだけです。

jsfiddle のデモ: http://jsfiddle.net/FDCh6/2/

function getArrayOfLines(theFunction){
    var theString = theFunction.toString();
    //now I'll need to generate an array of lines from the string, and then return the array
    var arrToReturn = theString.split("\n");
    return arrToReturn.slice(1, arrToReturn.length-1);
}

function functionToUse(){
    //This comment here should be included in the array of lines.
    //This is the second line that should be in the array.
}

alert(getArrayOfLines(functionToUse)); //get the array of lines from functionToUse
于 2013-04-06T20:07:15.517 に答える