[英]What is the difference between console.log(“Result” +vaRiable) and console.log(“Result”, vaRiable)?
[英]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.