Javascript多个“尝试" [英] Javascript multiple "try"s
本文介绍了Javascript多个“尝试"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们都知道JS中的基本转义机制:
We all know the basic escaping mechanism in JS:
try {
...
}
catch(err) {
..
}
我有一个JSON数据,我想在其中检查销售线索是否具有全名.如果不是这样,请尝试使用名字和姓氏字段(实际上我也用硬编码在这里空格也是一个问题)组成一个字段,最后如果所有失败都显示"No Name".
I have a JSON data in which I want to check if a lead has a full name. If not, try to compose one with first and last name fields (I actually hard code a space there which is a problem as well.) and finally if all fails show "No Name".
或使用伪代码:
try {
name = lead['Details']['Name']['Full'];
} else try {
name = lead['Details']['Name']['First'] + " " + lead['Details']['Name']['Last'];
} catch (e) {
name = "No Name";
}
有什么建议吗?
推荐答案
您可以将第二个try/catch块嵌套在第一个try/catch块的异常块中,如下所示:
You could nest your second try/catch block in the exception block of the first try/catch block as follows:
try {
name = lead['Details']['Name']['Full'];
} catch(ex0) {
try {
name = lead['Details']['Name']['First'] + " " + lead['Details']['Name']['Last'];
} catch (ex1) {
name = "No Name";
}
}
这是有效的语法,在功能上等同于您的要求
This is valid syntax, and functionally equivalent to what you're requiring
这篇关于Javascript多个“尝试"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文