0
我正在研究一个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)
我觉得我失去了一些东西非常非常明显的,但我没有看到它!
这只是正常:http://jsfiddle.net/55ym1xmj/2/ – vrijdenker 2014-09-28 11:18:05
所以这是你的实际代码,还是你调整一些东西在这里,以使示例小吗?因为否则在你的“真实”代码中可能会有某种竞争条件。 – vrijdenker 2014-09-28 11:20:56
您正在使用哪种浏览器。堆栈是Error的非标准属性。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack – 2014-09-28 11:44:07