__LINE__ equivalent in Javascript

前端 未结 7 1546
野趣味
野趣味 2021-01-01 19:14

Is there any way to get the source line number in Javascript, like __LINE__ for C or PHP?

7条回答
  •  甜味超标
    2021-01-01 19:36

    There is a way, although more expensive: throw an exception, catch it immediately, and dig out the first entry from its stack trace. See example here on how to parse the trace. The same trick can also be used in plain Java (if the code is compiled with debugging information turned on).

    Edit: Apparently not all browsers support this. The good news is (thanks for the comment, Christoph!) that some browsers export source file name and line number directly through the fileName and lineNumber properties of the error object.

提交回复
热议问题