0

我正在尝试从 JavaScript 函数中获取一组行。给定对特定函数的引用,我想返回一个数组,其中每个元素由函数源的单个连续行组成。

例子:

//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
}

主要是,我试图这样做,以便我可以评估函数的每一行(一次一行)。

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 回答