我想将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并调用Error()。stack在谷歌chrome中显示行号。
在谷歌铬堆栈看起来像这样:
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
}
}