我想知道如何将函数体转换为字符串?
function A(){
alert(1);
}
output = eval(A).toString() // this will come with function A(){ ~ }
//output of output -> function A(){ alert(1); }
//How can I make output into alert(1); only???
我想知道如何将函数体转换为字符串?
function A(){
alert(1);
}
output = eval(A).toString() // this will come with function A(){ ~ }
//output of output -> function A(){ alert(1); }
//How can I make output into alert(1); only???
如果你要做一些丑陋的事情,用正则表达式来做:
A.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
不要使用正则表达式。
const getBody = (string) => string.substring(
string.indexOf("{") + 1,
string.lastIndexOf("}")
)
const f = () => { return 'yo' }
const g = function (some, params) { return 'hi' }
const h = () => "boom"
console.log(getBody(f.toString()))
console.log(getBody(g.toString()))
console.log(getBody(h.toString())) // fail !
您可以将函数字符串化并通过删除其他所有内容来提取主体:
A.toString().replace(/^function\s*\S+\s*\([^)]*\)\s*\{|\}$/g, "");
但是,没有充分的理由这样做,而且toString
实际上并非在所有环境中都有效。
目前,开发人员在 Ecmascript 的新版本中使用箭头函数。
因此,我想在这里分享答案,这是弗兰克的答案
function getArrowFunctionBody(f) {
const matches = f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){?([\s\S]*)}?$/);
if (!matches) {
return null;
}
const firstPass = matches[1];
// Needed because the RegExp doesn't handle the last '}'.
const secondPass =
(firstPass.match(/{/g) || []).length === (firstPass.match(/}/g) || []).length - 1 ?
firstPass.slice(0, firstPass.lastIndexOf('}')) :
firstPass
return secondPass;
}
const K = (x) => (y) => x;
const I = (x) => (x);
const V = (x) => (y) => (z) => z(x)(y);
const f = (a, b) => {
const c = a + b;
return c;
};
const empty = () => { return undefined; };
console.log(getArrowFunctionBody(K));
console.log(getArrowFunctionBody(I));
console.log(getArrowFunctionBody(V));
console.log(getArrowFunctionBody(f));
console.log(getArrowFunctionBody(empty));
原始问题在这里