简体   繁体   中英

Generate an array of source lines from a JavaScript function

I'm trying to obtain an array of lines from a JavaScript function. Given a reference to a specific function, I would like to return an array where each element consists of a single consecutive line of the function's source.

Example:

//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." ]

Here's where I'm at:

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
}

Mainly, I'm trying to do this so that I can evaluate each line of a function (one line at a time).

Simple - all you need to do is use stringtoSplit.split("\\n") to obtain an array of lines.

Demo on 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM