Is there a way to print out the line number of a js file in the console log

邮差的信 提交于 2019-12-02 00:57:14

问题


For debugging purposes, I usually use something like console.log('line number #').

Not sure if it's the best way to handle it but I think it would be helpful if I can just print out the line number of the line where I'm putting the console.log() dynamically.

Let's say:

1    //do something
2    if(file){
3        console.log('Line 3');
4        $('#uploads').css({ 'height' : 'auto' });
5    } else { 
6       console.log(getLineNumber());   //just an example
7       $('#tags').val(temp);
8    }

In the above, if I happen to remove line 1 for instance, line 3 will be technically incorrect as the line number is decremented by 1 but the log will still show 3. But in line 6, suppose getLineNumber() returns the line number, then it will still make sense even after a line above has been removed.

So is there an easy way which acts like getLineNumber()?


回答1:


You can use onerror event handler for that.

See the last example on this page: http://www.tutorialspoint.com/javascript/javascript_error_handling.htm

Direct link to example: http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=javascript_40



来源:https://stackoverflow.com/questions/9290000/is-there-a-way-to-print-out-the-line-number-of-a-js-file-in-the-console-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!