【问题标题】:How to format the function body when using toString()使用 toString() 时如何格式化函数体
【发布时间】:2016-06-24 11:26:01
【问题描述】:

假设我从一个缩小的 JavaScript 文件中获得了这个函数:

function fn(){console.log('Lorem');console.log('Ipsum');}

我想在调用时得到一个漂亮的打印缩进版本:

console.log(fn.toString());

预期输出:

function fn() {
    console.log('Lorem');
    console.log('Ipsum');
}

代替:

function fn(){console.log('Lorem');console.log('Ipsum');}

无论如何要这样做?

【问题讨论】:

    标签: javascript formatting google-chrome-devtools firebug console.log


    【解决方案1】:

    JavaScript 没有执行此操作的内置函数。因此,如果您想以编程方式进行漂亮的打印,则必须手动进行。 要获取函数的源代码,有一个非标准的Function.prototype.toSource() 函数,但只有 Firefox 支持。涵盖您的示例的一个非常简单的漂亮打印功能是:

    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 源代码。

    萤火虫:

    Firefox 开发工具:

    Chrome 开发工具:

    【讨论】:

      【解决方案2】:

      js-beautify 库在打印 JS 代码方面做得非常好

      http://jsbeautifier.org/

      https://github.com/beautify-web/js-beautify

      // Script inclusion
      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open('GET', 'https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.4/beautify.js', false);
      xmlHttp.send(null);
      var jsCode = xmlHttp.responseText;
      
      var script = document.createElement("script");
      script.innerHTML = jsCode;
      document.head.appendChild(script);
      
      // Usage
      function fn(){console.log('Lorem');console.log('Ipsum');}
      js_beautify(fn.toString());
      
      // Output
      function fn() {
          console.log('Lorem');
          console.log('Ipsum');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-22
        • 1970-01-01
        • 2013-03-29
        • 1970-01-01
        • 2017-03-16
        相关资源
        最近更新 更多