問題描述
我正在嘗試將 console.log 作為純 JavaScript 中的字符串.我的輸入是一個腳本,我不熟悉,我想把console.log中的所有消息收集成一個字符串.
I'm trying to get the console.log as string in pure JavaScript. My input is a script, which I'm not familiar with, and I want to collect all the messages in the console.log into a string.
例如:
function doSomething(){
console.log("start");
console.log("end");
var consoleLog = getConsoleLog();
return consoleLog;
}
function getConsoleLog(){
// How to implement this?
}
alert(doSomething());
JSFiddle 鏈接
請注意,我不需要提醒日志 - 這只是測試功能的一個簡單示例.我得對日志的內(nèi)容做一些操作.
Note that I do not need to alert the log - this is just a simple example of testing the functionality. I'll have to do some operations on the log's content.
推薦答案
你可以在使用之前覆蓋 console.log
方法:
You could overwrite console.log
method before using it:
var logBackup = console.log;
var logMessages = [];
console.log = function() {
logMessages.push.apply(logMessages, arguments);
logBackup.apply(console, arguments);
};
使用 apply
和 arguments
保留正確的 console.log
行為,即您可以通過一次調(diào)用添加多個日志消息.
Using apply
and arguments
preserves the correct console.log
behaviour, i.e. you can add multiple log messages with a single call.
它將所有新的 console.log
消息推送到 logMessages
數(shù)組.
It will push all new console.log
messages to logMessages
array.
這篇關(guān)于如何在 JavaScript 中將 console.log 內(nèi)容作為字符串獲取的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!