简体   繁体   English

javascript多次尝试捕获

[英]javascript multiple try catch

I read this article Multiple try-catch or one?我读了这篇文章多次尝试捕获还是一次? and was wondering if there was a better way?并且想知道是否有更好的方法? Is there a way to just ignore the bad lines of code?有没有办法忽略坏的代码行? My problem is I need to load multiple variables from objects that may or may not exist.我的问题是我需要从可能存在或不存在的对象加载多个变量。 Thanks everyone谢谢大家

 toparcv = document.getElementsByName("attribute[425]")[0].value; toparcv = document.getElementsByName("attribute[423]")[0].value; toparcv = document.getElementsByName("attribute[424]")[0].value; toparcv = document.getElementsByName("attribute[426]")[0].value; toparcv = document.getElementsByName("attribute[434]")[0].value; bottomarcv = document.getElementsByName("attribute[271]")[0].value; bottomarcv = document.getElementsByName("attribute[265]")[0].value; bottomarcv = document.getElementsByName("attribute[268]")[0].value; bottomarcv = document.getElementsByName("attribute[369]")[0].value; bottomarcv = document.getElementsByName("attribute[433]")[0].value; console.log(toparcv); console.log(bottomarcv);

im trying to read a textbox from a website that randomly generates the name from about 10 different names by adding 433 or 268.我试图从一个网站读取一个文本框,该网站通过添加 433 或 268 从大约 10 个不同的名称中随机生成名称。

You can cover all the bottommarcv assignments like this:你可以像这样覆盖所有的bottommarcv分配:

[271, 265, 268, 369, 433].forEach(function(num) {
    var list = document.getElementsByName("attribute[" + num + "]");
    if (list && list.length) {
        bottomarcv = list[0].value;
    }
});

This code pre-preemptively avoids an exception by checking the integrity of variables before referencing properties on them and because it's using a loop to examine each element, it can use only one if statement for all the values.这段代码通过在引用变量的属性之前检查它们的完整性来预先避免异常,并且因为它使用循环来检查每个元素,所以它只能对所有值使用一个if语句。

It is a little odd to be assigning them all to the same variable.将它们全部分配给同一个变量有点奇怪。 Do you really only want the last one that has a value to be used here?您真的只希望在此处使用具有值的最后一个吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM