【发布时间】:2016-10-10 03:15:01
【问题描述】:
我读了这篇文章Multiple try-catch or one?,想知道是否有更好的方法?有没有办法忽略不好的代码行?我的问题是我需要从可能存在或不存在的对象中加载多个变量。 谢谢大家
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);
我试图从一个网站中读取一个文本框,该网站通过添加 433 或 268 从大约 10 个不同的名称中随机生成名称。
【问题讨论】:
-
听起来您应该使用
if语句来检查对象是否存在。 -
把
try/catch放在抛出异常的代码周围,而不是整个块。 -
也许您应该使用循环或函数,这样您就不需要为每个变量重复代码。
-
if 语句应该是 15 if else's 还是我疯了?
-
@zackmcdonald - 你能提供一些代码来准确显示你正在尝试做什么,或者一个例子吗?似乎您遇到了一个很容易解决的问题,但您只是在使用
try...catch的东西走错了路……
标签: javascript try-catch