I'm using console.log(var_name); to debug JS code in chrome and am wondering, is there a way to output to the console the line at which the current function was called?
-
I've just solved my bug everyone... thanks to all who replied!!!flea whale– flea whale2011-11-30 16:13:00 +00:00Commented Nov 30, 2011 at 16:13
Add a comment
|
2 Answers
You can get the stack trace with the following:
(new Error).stack;
You could then use a regular expression to filter out the line number: http://jsfiddle.net/8wA74/.
var stack = (new Error).stack.split("\n"),
line = /:(\d+):/.exec(stack[1]); // 1 is stack depth, format is "url:line:char"
console.log("Current function was called on line " + line[1]);
// this 1 is the number of the group in regexp
2 Comments
flea whale
thanks @pimvdb, this is helpful to an extent although it's actually giving me the line where (new Error) is, not the line where the function that encompasses that was called.
pimvdb
@Jimmy_Bob: Then you can try changing
stack[1] to stack[2], which is one level deeper in the stack trace.Not that i know of, but wouldnt it be possible to set a breakpoint instead? That surely has a stacktrace visible.
Just try to click the linenumber in the dev. console, it'll show a blue arrow and next time it hits it'll show you the stacktrace.
1 Comment
flea whale
thanks for this, I'm sure breakpoints will be easier than console logging when I get the hang of them