JavaScript에서 현재 줄 번호를 어떻게 확인할 수 있습니까?
JavaScript에는 현재 실행중인 문의 줄 번호를 결정하는 메커니즘이 있습니까 (그렇다면 무엇입니까)?
var thisline = new Error().lineNumber
사용중인 환경에서 작동하지 않는 경우 다음을 시도해 볼 수 있습니다.
var stack = new Error().stack
그런 다음 스택에서 줄 번호를 찾으십시오.
당신이 사용할 수있는
function test(){
console.trace();
}
test();
다른 브라우저와 브라우저 버전간에 좀 더 이식성이 뛰어납니다 (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];
}
일부 마크를 찾기 위해 함수의 소스를 구문 분석 할 수 있습니다.
다음은 간단한 예입니다 (예, 약간 엉망입니다).
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;
}
당신은 시도 할 수 있습니다:
window.onerror = handleError;
function handleError(err, url, line){
alert(err + '\n on page: ' + url + '\n on line: ' + line);
}
그런 다음 알고 싶은 곳에 오류를 발생시킵니다 (과도하게 원하지는 않지만 디버깅하는 경우 도움이 될 수 있습니다.).
참고 : window.onerror
WebKit 또는 Opera에서 정의 / 처리되지 않음 (마지막으로 확인)
코드에 다음 스 니펫을 삽입하십시오.
console.debug("line:", /\(file:[\w\d/.-]+:([\d]+)/.exec(new Error().stack)[1]);
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__ ?>
(That's assuming you have PHP short tags enabled, obviously.)
So, for example, in javascript you can say:
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.
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.
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:
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.
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 stackoverflow 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:
<!-- *** 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.
'program tip' 카테고리의 다른 글
새 프로젝트는 log4j 대신 logback을 사용해야합니까? (0) | 2020.10.17 |
---|---|
"text-align : justify;"를 사용하지 않아야합니까? (0) | 2020.10.17 |
클러스터형 인덱스는 고유해야합니까? (0) | 2020.10.17 |
Git-메서드 / 함수의 변경 내역을 보려면 어떻게해야합니까? (0) | 2020.10.17 |
PostgreSQL에서 두 데이터베이스 간의 데이터를 비교하는 방법은 무엇입니까? (0) | 2020.10.17 |