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.
You can cover all the bottommarcv
assignments like this:
[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.
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.