How can I determine the current line number in JavaScript?

前端 未结 8 1694
自闭症患者
自闭症患者 2020-11-27 13:46

Does JavaScript have a mechanism for determining the line number of the currently executing statement (and if so, what is it)?

8条回答
  •  悲&欢浪女
    2020-11-27 14:08

    If your code is JavaScript + PHP, then the current PHP line number is available in JavaScript as a literal constant, because it's available in PHP as  

    (That's assuming you have PHP short tags enabled, obviously.)

    So, for example, in JavaScript you can say:

    this_php_line_number = ;
    

    However, if you are not careful, the PHP line number might be different from the JavaScript line number, because PHP "eats" source lines before the browser ever sees them. So the problem becomes ensuring that your PHP and JavaScript line numbers are the same. If they're different it makes using the browser's JavaScript debugger a lot less pleasant.

    You can ensure the line numbers are the same by including a PHP statement that writes the correct number of newlines needed to synchronize server-side (PHP) and browser-side (JavaScript) line numbers.

    Here's what my code looks like:

    
    
    
    
      
      
    
    
    
    
      My web page title
    
    ...lots of HTML and JavaScript stuff here...
    
    
    
    
    

    The key is this PHP statement:

    echo str_repeat("\n",__LINE__-6);
    

    That spits out enough newlines to make the line number seen by JavaScript be the same as the PHP line number. All the PHP function definitions, etc. are at the top, ahead of that line.

    After that line, I restrict my use of PHP to code that doesn't change the line numbers.

    The "-6" accounts for the fact that my PHP code starts on line 8. If you start your PHP code earlier, you'll reduce that number. Some people put their PHP right at the very top, even ahead of the DOCTYPE.

    (The meta viewport line disables Android Chrome "font boosting" per this Stack Overflow Q&A: Chrome on Android resizes font. Consider it boilerplate, which every web page needs.)

    The following line is just for verifying that I haven't made a mistake. Viewed in the browser's debugger, or by right-click / save-web-page, it becomes an HTML comment which shows the correct source file name and line number:

    
    

    becomes:

    
    

    Now, wherever I see a line number, whether it's in an error message or in the JavaScript debugger, it's correct. PHP line numbers and JavaScript line numbers are always consistent and identical.

提交回复
热议问题