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