【问题标题】:How to store console.log() result as an object / variable?如何将 console.log() 结果存储为对象/变量?
【发布时间】:2013-08-20 22:25:03
【问题描述】:

我想将 console.log() 函数的输出保存为对象或变量。 我主要对接收对象结果以及行号感兴趣。

以下只是为了演示,我在寻找什么:

var myobj = {"key":"value"}; // (<< in 'myjs.js, line 123)
var mylog = console.log( myobj );

// output mylog: {"key":"value"}, myjs.js:123

提前感谢您的帮助!

【问题讨论】:

  • console.log() 不返回任何值...所以使用 console.log 是不可能的
  • 事实上myObjmyLog,分配它就行了
  • 从技术上讲,您可以覆盖控制台原型中的函数,但这似乎是个糟糕的主意。
  • 要将输出保存为字符串还是对象?
  • 我更喜欢作为对象,但由于我主要对行号感兴趣,因此作为字符串也会有很大帮助。

标签: javascript jquery debugging console


【解决方案1】:

您可以使用new Error().lineNumber 获取行号 有关确定行号的更多信息 - determining line number

【讨论】:

  • 这是一个非常有趣的提示,谢谢!不幸的是,Error() 似乎不像 console() 那样跨浏览器兼容。如果应该有办法捕捉控制台输出,我更喜欢这个。到目前为止,这个非常接近!
【解决方案2】:

您可以覆盖 console.log 并在谷歌浏览器中调用 Error().stack 它显示行号。

在谷歌浏览器堆栈中看起来像这样:

Error
    at Error (<anonymous>)
    at Console.console.log (http://localhost/test.js:6:27)
    at foo (http://localhost/test.js:13:13)
    at http://localhost/test.js:16:1 

所以代码需要获取 3 行并删除 "at http://localhost" 和字符数

(function(log) {
    console.log = function(o) {
        var stack = Error().stack.split('\n');
        log.call(console, JSON.stringify(o) + ', ' + stack[3].
            replace(/.*http:\/\/[^\/]*|:[0-9]+\)$/g, ''));
    };
})(console.log);


function foo() {
    console.log({foo: 'bar'});
}

foo();

【讨论】:

    【解决方案3】:

    尝试保存 myObj 对象。这就是记录器将记录的内容。

    【讨论】:

    • 我也想收到行号。
    【解决方案4】:

    你可以通过链接Read the output of console.log试试这个

    function myFunctionThatMightHaveAnError(){
        // instead of just failing silently, actually throw an error
        $.error("My special error");
    }
    // Then use a try/catch block to handle it
    try {
        myFunctionThatMightHaveAnError();
        alert("No error!"); // this line would only run if no error were thrown
    } catch (e) {
        if(e == "My special error") {
            // Handle error
        }
    }
    

    【讨论】:

    • 谢谢!我自己做了一个类似的解决方法,但我错过了如何捕捉行号。
    • 这段代码实际上是在捕获函数的错误输出,所以从技术上讲,您没有阅读 console.log,因为您无法阅读控制台....据我所知,因此您无法使用此代码捕获行号...或任何
    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多