【发布时间】:2014-09-28 11:03:08
【问题描述】:
我正在开发一个 javascript 调试工具,我现在需要的是从堆栈跟踪的末尾获取行号。所以我编写了以下函数来获取堆栈跟踪,删除前几行,然后我打算使用 indexOf(':') 来获取行号。但是,我不断收到“无法调用未定义的方法‘子字符串’”错误。好的,这应该很容易修复,但请稍等 - console.log 建议文件已定义。谁能解释我哪里出错了。
代码:
var getLine = function () {
var stack = (new Error('dummy').stack).toString();
var stackLines = stack.split('\n');
stackLines = stackLines.filter(function (element) {
var exclude = [ "Error: dummy", "graph.js" ];
for (var i = 0; i < exclude.length; i++) {
if (element.indexOf(exclude[i]) !== -1) {
return false;
}
}
return true;
});
console.log("1 array", stackLines);
console.log("2 element", stackLines[0]);
console.log("3 typeof element", typeof (stackLines[0]));
console.log("4 huh?", stackLines[0].substring(1));
}
输出:
1 array [ ' at Object.<anonymous> (E:\\Development\\james\\main.js:52:18)',
' at Module._compile (module.js:456:26)' ]
2 element at Object.<anonymous> (E:\Development\james\main.js:52:18)
3 typeof element string
E:\Development\james\graph.js:47
console.log("huh?", stackLines[0].substring(1));
^
TypeError: Cannot call method 'substring' of undefined
更奇怪的是 - 如果我将 console.log 语句包装在 try/catch 中,那么它执行时不会出错?
代码:
var getLine = function () {
var stack = (new Error('dummy').stack).toString();
var stackLines = stack.split('\n');
stackLines = stackLines.filter(function (element) {
var exclude = [ "Error: dummy", "graph.js" ];
for (var i = 0; i < exclude.length; i++) {
if (element.indexOf(exclude[i]) !== -1) {
return false;
}
}
return true;
});
try {
console.log("array", stackLines);
console.log("element", stackLines[0]);
console.log("typeof element", typeof (stackLines[0]));
console.log("huh?", stackLines[0].substring(stackLines[0].indexOf(":")));
} catch (e){
console.log("error",e);
}
输出:
1 array [ ' at Object.<anonymous> (E:\\Development\\james\\main.js:52:18)',
' at Module._compile (module.js:456:26)' ]
2 element at Object.<anonymous> (E:\Development\james\main.js:52:18)
3 typeof element string
4 huh? :\Development\james\main.js:52:18)
我觉得我错过了一些非常明显的东西,但我没有看到它!
【问题讨论】:
-
这是您的实际代码,还是您在此处调整了一些内容以使示例更小?因为否则在您的“真实”代码中可能存在某种竞争条件。
-
您使用的是哪个浏览器。 Stack 是 Error 的非标准属性。见developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
@Haim — 这个问题被标记为
node.js,所以大概根本没有浏览器。 -
@JamesG — 如果您提供足够的代码来重现问题(即测试数据和对您的函数的调用),将会有所帮助。
标签: javascript node.js undefined