假设我从一个缩小的 JavaScript 文件中获得了这个函数:
function fn(){console.log('Lorem');console.log('Ipsum');}
我想在调用时得到一个 pretty-print 缩进版本:
console.log(fn.toString());
预期输出:
function fn() {
console.log('Lorem');
console.log('Ipsum');
}
代替:
function fn(){console.log('Lorem');console.log('Ipsum');}
无论如何都要这样做?
最佳答案
JavaScript 没有内置函数来执行此操作。因此,如果您想以编程方式进行 pretty-print ,则必须手动进行。
要获取函数的源代码,有一个非标准的 Function.prototype.toSource()
功能,不过只有 Firefox 支持。涵盖您的示例的一个非常简单的 pretty-print 功能是:
function prettyPrint(source) {
let formattedSource = fn.toSource ? fn.toSource() : "";
// Add line breaks after curly braces and semicolons
formattedSource = formattedSource.replace(/([{};])/g, "$1\n");
// Add space after opening curly brace
formattedSource = formattedSource.replace(/(\S)\{/g, "$1 {");
// Indent lines ending with a semicolon
formattedSource = formattedSource.replace(/^(.*?);/gm, " $1;");
return formattedSource;
}
console.log(prettyPrint(fn));
综上所述,不同的开发人员工具集成了选项,可以在其调试器中漂亮地打印 JavaScript 源代码。
Firebug :
Firefox 开发者工具:
Chrome 开发者工具:
关于javascript - 使用 toString() 时如何格式化函数体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902579/