JavaScript 有一种机制可以确定当前执行语句的行号吗?如果有,它是什么?
var thisline = new Error().lineNumber
如果在你所使用的环境中无法工作,可以尝试:
var stack = new Error().stack
然后通过查找堆栈来获取行号。
lineNumber
属性,也没有stack
:-)。 - Andy E您可以使用:
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];
}
var frameRE = /:(\d+:\d+)[^\d]*$/;
这样会更有用,特别是当JS被压缩成一行时。 - Quinn Comendantfunction 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;
}
将以下代码片段注入到您的代码中:
console.debug("line:", /\(file:[\w\d/.-]+:([\d]+)/.exec(new Error().stack)[1]);
TypeError: /\(http:[\w\d/.-]+:([\d]+)/.exec(...) is null
的错误信息。 - RyanthrowAndResume(resumeFunction);
,它将存储 resumeFunction,抛出错误,在错误处理程序中记录详细信息,然后调用 resumeFunction 来继续你的程序。 - Mark Bolusmjakconst line = new Error().stack.match(/(:[\d]+)/)[0].replace(':','')
console.log(line)
'use strict';
function thisLine() {
let line;
const _prepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => {
line = stack[1].getLineNumber();
};
const e = new Error();
e.stack;
Error.prepareStackTrace = _prepareStackTrace;
return line;
}
if (require.main === module) {
console.log('this line is', thisLine());
}
var getPos = (toGet = null) => {
let stack = String(new Error().stack);
let calledFrom = String((stack.split(`\n`)).filter(item => item).at(-1));
calledFrom = calledFrom.startsWith('@') ? calledFrom.slice(1) : calledFrom;
let items = {
stack: stack,
calledFrom: calledFrom,
}
let lineCol = String(calledFrom).match(/(\:)([0-9]){1,}(:([0-9]).?)$/g)[0];
lineCol = String(lineCol).split(':').filter(item => item)
items['lineCol'] = lineCol.join(':');
items['line'] = lineCol.length == 2 ? lineCol[0] : null;
items['col'] = lineCol.length == 2 ? lineCol[1] : null;
toGet = toGet ? String(toGet) : null;
if (toGet && !Object.keys(items).includes(toGet)) {
return null;
}
return items[`${toGet}`] ?? items;
}
var __LINE__ = () => getPos('line');
// Usage
/*
console.log(getPos())
console.log(__LINE__())
console.log(getPos('lineCol'))
console.log(getPos('line'))
console.log(getPos('col'))
console.log(getPos('calledFrom'))
console.log(getPos('stack'))
*/
从Error.stack中无法纯粹地获取行号,因为在Angular中,行号是编译代码的行号。但是可以获取创建错误的方法信息。此代码片段中的Logger类将此信息添加到新的日志记录条目中。
https://stackblitz.com/edit/angular-logger?file=src/app/Logger/logger.ts