Does JavaScript have a mechanism for determining the line number of the currently executing statement (and if so, what is it)?
JavaScript是否有确定当前执行语句的行号的机制(如果有,是什么机制)?
7 个解决方案
#1
53
var thisline = new Error().lineNumber
var thisline = new Error().lineNumber
If that doesn't work in whatever environment you're using, you can try:
如果在你所使用的任何环境中都不适用,你可以试试:
var stack = new Error().stack
var stack = new Error().stack
Then hunt through the stack for the line number.
然后在堆栈中搜索行号。
#2
18
A bit more portable between different browsers and browser versions (should work in Firefox, Chrome and IE10+):
在不同的浏览器和浏览器版本之间有更好的可移植性(应该适用于Firefox、Chrome和IE10+):
function ln() {
var e = new Error();
if (!e.stack) try {
// IE requires the Error to actually be throw or else the Error's 'stack'
// property is undefined.
throw e;
} catch (e) {
if (!e.stack) {
return 0; // IE < 10, likely
}
}
var stack = e.stack.toString().split(/\r\n|\n/);
// We want our caller's frame. It's index into |stack| depends on the
// browser and browser version, so we need to search for the second frame:
var frameRE = /:(\d+):(?:\d+)[^\d]*$/;
do {
var frame = stack.shift();
} while (!frameRE.exec(frame) && stack.length);
return frameRE.exec(stack.shift())[1];
}
#3
18
you can use
您可以使用
function test(){
console.trace();
}
test();
#4
3
You can try to parse a source of a function to seek some marks.
Here is a quick example (yes, it's messed a little).
您可以尝试解析函数的一个源来寻找一些标记。这里有一个简单的例子(是的,有点混乱)。
function foo()
{
alert(line(1));
var a;
var b;
alert(line(2));
}
foo();
function line(mark)
{
var token = 'line\\(' + mark + '\\)';
var m = line.caller.toString().match(
new RegExp('(^(?!.*' + token + '))|(' + token + ')', 'gm')) || [];
var i = 0;
for (; i < m.length; i++) if (m[i]) break;
return i + 1;
}
#5
1
you can try:
你可以尝试:
window.onerror = handleError;
function handleError(err, url, line){
alert(err + '\n on page: ' + url + '\n on line: ' + line);
}
then throw an error where you want to know (not overly desired, but it might help you if you are debugging.
然后在您想知道的地方抛出一个错误(不是特别需要,但是如果您正在调试的话,它可能会帮助您。
Note: window.onerror
isn't defined/handled in WebKit or Opera (last time I checked)
注意:窗口。onerror不在WebKit或Opera中定义/处理(上次检查时)
#6
1
inject the following snippet to your code:
将以下代码片段注入您的代码:
console.debug("line:", /\(file:[\w\d/.-]+:([\d]+)/.exec(new Error().stack)[1]);
#7
0
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 <?= __LINE__ ?>
如果您的代码是javascript + PHP,那么当前的PHP行号作为一个常量在javascript中可用,因为在PHP中它作为
(That's assuming you have PHP short tags enabled, obviously.)
(显然,这是假设您启用了PHP短标记。)
So, for example, in javascript you can say:
例如,在javascript中,你可以说:
this_php_line_number = <?= __LINE__ ?>;
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.
但是,如果不小心,PHP行号可能与javascript行号不同,因为PHP在浏览器看到源行之前“吃”源行。因此问题就变成了确保PHP和javascript行号是相同的。如果它们是不同的,那么使用浏览器的javascript调试器就不那么愉快了。
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 brower-side (javascript) line numbers.
可以通过包含一个PHP语句来确保行号是相同的,该语句写入了同步服务器端(PHP)和浏览器端(javascript)行号所需的正确新行数。
Here's what my code looks like:
我的代码是这样的:
<!DOCTYPE html>
<html lang="en">
<!-- Copyright 2016, 2017, me and my web site -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, user-scalable=yes">
<?php
...lottsa PHP stuff here, including all PHP function definitions ...
echo str_repeat("\n",__LINE__-6); # synchronize PHP and Javascript line numbers
?>
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->
<title>My web page title</title>
...lottsa HTML & Javascript stuff here...
</body>
</html>
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->
The key is this PHP statement:
关键是这个PHP语句:
echo str_repeat("\n",__LINE__-6);
That's 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.
这就产生了足够的新行,使javascript看到的行号与PHP行号相同。所有的PHP函数定义等等都在上面,在这一行的前面。
After that line, I restrict my use of PHP to code that doesn't change the line numbers.
在这一行之后,我将PHP限制为不更改行号的代码。
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.
“-6”表示PHP代码从第8行开始。如果您更早地启动PHP代码,您将会减少这个数字。有些人把PHP放在最顶端,甚至在DOCTYPE之前。
(The meta viewport line disables Android Chrome "font boosting" per this * Q&A: Chrome on android resizes font . Consider it boilerplate, which every web page needs.)
(meta viewport行禁止Android Chrome在这个*问答页面上显示“字体增强”:Android上的Chrome可以调整字体大小。考虑它的样板文件,这是每个网页都需要的。
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:
下面这行只是为了验证我没有犯错误。在浏览器的调试器中查看,或者通过右键单击/保存-web页面查看,它会变成一个HTML注释,显示正确的源文件名和行号:
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->
becomes:
就变成:
<!-- *** this is line 1234 of my_file.php *** -->
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.
现在,无论我在哪里看到行号,无论是在错误消息中还是在javascript调试器中,它都是正确的。PHP行号和javascript行号总是一致和相同的。
#1
53
var thisline = new Error().lineNumber
var thisline = new Error().lineNumber
If that doesn't work in whatever environment you're using, you can try:
如果在你所使用的任何环境中都不适用,你可以试试:
var stack = new Error().stack
var stack = new Error().stack
Then hunt through the stack for the line number.
然后在堆栈中搜索行号。
#2
18
A bit more portable between different browsers and browser versions (should work in Firefox, Chrome and IE10+):
在不同的浏览器和浏览器版本之间有更好的可移植性(应该适用于Firefox、Chrome和IE10+):
function ln() {
var e = new Error();
if (!e.stack) try {
// IE requires the Error to actually be throw or else the Error's 'stack'
// property is undefined.
throw e;
} catch (e) {
if (!e.stack) {
return 0; // IE < 10, likely
}
}
var stack = e.stack.toString().split(/\r\n|\n/);
// We want our caller's frame. It's index into |stack| depends on the
// browser and browser version, so we need to search for the second frame:
var frameRE = /:(\d+):(?:\d+)[^\d]*$/;
do {
var frame = stack.shift();
} while (!frameRE.exec(frame) && stack.length);
return frameRE.exec(stack.shift())[1];
}
#3
18
you can use
您可以使用
function test(){
console.trace();
}
test();
#4
3
You can try to parse a source of a function to seek some marks.
Here is a quick example (yes, it's messed a little).
您可以尝试解析函数的一个源来寻找一些标记。这里有一个简单的例子(是的,有点混乱)。
function foo()
{
alert(line(1));
var a;
var b;
alert(line(2));
}
foo();
function line(mark)
{
var token = 'line\\(' + mark + '\\)';
var m = line.caller.toString().match(
new RegExp('(^(?!.*' + token + '))|(' + token + ')', 'gm')) || [];
var i = 0;
for (; i < m.length; i++) if (m[i]) break;
return i + 1;
}
#5
1
you can try:
你可以尝试:
window.onerror = handleError;
function handleError(err, url, line){
alert(err + '\n on page: ' + url + '\n on line: ' + line);
}
then throw an error where you want to know (not overly desired, but it might help you if you are debugging.
然后在您想知道的地方抛出一个错误(不是特别需要,但是如果您正在调试的话,它可能会帮助您。
Note: window.onerror
isn't defined/handled in WebKit or Opera (last time I checked)
注意:窗口。onerror不在WebKit或Opera中定义/处理(上次检查时)
#6
1
inject the following snippet to your code:
将以下代码片段注入您的代码:
console.debug("line:", /\(file:[\w\d/.-]+:([\d]+)/.exec(new Error().stack)[1]);
#7
0
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 <?= __LINE__ ?>
如果您的代码是javascript + PHP,那么当前的PHP行号作为一个常量在javascript中可用,因为在PHP中它作为
(That's assuming you have PHP short tags enabled, obviously.)
(显然,这是假设您启用了PHP短标记。)
So, for example, in javascript you can say:
例如,在javascript中,你可以说:
this_php_line_number = <?= __LINE__ ?>;
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.
但是,如果不小心,PHP行号可能与javascript行号不同,因为PHP在浏览器看到源行之前“吃”源行。因此问题就变成了确保PHP和javascript行号是相同的。如果它们是不同的,那么使用浏览器的javascript调试器就不那么愉快了。
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 brower-side (javascript) line numbers.
可以通过包含一个PHP语句来确保行号是相同的,该语句写入了同步服务器端(PHP)和浏览器端(javascript)行号所需的正确新行数。
Here's what my code looks like:
我的代码是这样的:
<!DOCTYPE html>
<html lang="en">
<!-- Copyright 2016, 2017, me and my web site -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, user-scalable=yes">
<?php
...lottsa PHP stuff here, including all PHP function definitions ...
echo str_repeat("\n",__LINE__-6); # synchronize PHP and Javascript line numbers
?>
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->
<title>My web page title</title>
...lottsa HTML & Javascript stuff here...
</body>
</html>
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->
The key is this PHP statement:
关键是这个PHP语句:
echo str_repeat("\n",__LINE__-6);
That's 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.
这就产生了足够的新行,使javascript看到的行号与PHP行号相同。所有的PHP函数定义等等都在上面,在这一行的前面。
After that line, I restrict my use of PHP to code that doesn't change the line numbers.
在这一行之后,我将PHP限制为不更改行号的代码。
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.
“-6”表示PHP代码从第8行开始。如果您更早地启动PHP代码,您将会减少这个数字。有些人把PHP放在最顶端,甚至在DOCTYPE之前。
(The meta viewport line disables Android Chrome "font boosting" per this * Q&A: Chrome on android resizes font . Consider it boilerplate, which every web page needs.)
(meta viewport行禁止Android Chrome在这个*问答页面上显示“字体增强”:Android上的Chrome可以调整字体大小。考虑它的样板文件,这是每个网页都需要的。
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:
下面这行只是为了验证我没有犯错误。在浏览器的调试器中查看,或者通过右键单击/保存-web页面查看,它会变成一个HTML注释,显示正确的源文件名和行号:
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->
becomes:
就变成:
<!-- *** this is line 1234 of my_file.php *** -->
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.
现在,无论我在哪里看到行号,无论是在错误消息中还是在javascript调试器中,它都是正确的。PHP行号和javascript行号总是一致和相同的。