检测 javascript 中的错误(在代码中)并采取相应措施
Detect error in javascript (in code) and act accordingly
我有一些 var data
可能有 data[0].substring(1)[1]
也可能没有(关于 .substring())
我无法更改我收到的数据,它也没有以指定的格式出现。请不要问这个问题,这个问题的想法就是在这种情况下回答。
我试过这样做
if(data[0].substring(1)[1]){
}
但是 Cannot read property 'substring' of undefined
无论如何它都失败了,所以现在我不确定我应该怎么做。
这可能吗?有解决方法吗?
您应该在尝试访问之前检查 data[0]
是否存在:
if(data[0] && data[0].substring(..)) {
...
}
使用try/catch/finally
:
var txt;
try{
txt=data[0].substring(1)[1];
}
catch(e){
console.log(e);
console.log("The variable does not contain this data."); // at your own choice
}
finally{
if(txt!=undefined){
// do stuff with txt
}
}
我有一些 var data
可能有 data[0].substring(1)[1]
也可能没有(关于 .substring())
我无法更改我收到的数据,它也没有以指定的格式出现。请不要问这个问题,这个问题的想法就是在这种情况下回答。
我试过这样做
if(data[0].substring(1)[1]){
}
但是 Cannot read property 'substring' of undefined
无论如何它都失败了,所以现在我不确定我应该怎么做。
这可能吗?有解决方法吗?
您应该在尝试访问之前检查 data[0]
是否存在:
if(data[0] && data[0].substring(..)) {
...
}
使用try/catch/finally
:
var txt;
try{
txt=data[0].substring(1)[1];
}
catch(e){
console.log(e);
console.log("The variable does not contain this data."); // at your own choice
}
finally{
if(txt!=undefined){
// do stuff with txt
}
}