簡體   English   中英

如何將console.log()結果存儲為對象/變量?

[英]How to store console.log() result as an object / variable?

我想將console.log()函數的輸出另存為對象或變量。 我主要對接收對象結果以及行號感興趣。

以下只是演示,我在尋找什么:

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

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

在此先感謝您的幫助!

您可以使用new Error().lineNumber獲取行號有關確定行號的更多信息- 確定行號

您可以覆蓋console.log並在Google Chrome中調用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();

嘗試保存myObj對象。 這就是記錄器將記錄的內容。

您可以從鏈接閱讀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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM