如果变量未定义,try / catch(其中之一)是防止错误发生的最佳方法吗?
我被警告说这篇文章可能过于主观,但我只编程了几周,所以我想知道。
到目前为止,我一直在使用 try/catch 语句我的 JS 是为了防止在函数运行时未定义变量的情况下抛出错误,但这是唯一有效的方法吗?
I was warned that this post could be too subjective, but I've only been programming for a few weeks, so I'd like to know.
So far I've been using try/catch statements in my JS to keep from throwing errors in case a variable isn't defined when a function is run, but is that the only efficient way to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您使用的是浏览器,则可以使用
window.foo
测试全局变量。例如:如果我正在阅读代码,我更愿意阅读此内容而不是
try { foo } catch { ... }
。另外,请注意三重等于:这是必要的,因为如果
window.foo
为null
,则window.foo == undefined
将是 < em>true,而window.foo === undefined
将为 false (你想要的)。If you're in a browser, you can test for global variables using
window.foo
. Eg:If I was reading code, I would prefer to read this than
try { foo } catch { … }
.Also, note the triple equals: that is necessary because, if
window.foo
isnull
, thenwindow.foo == undefined
will be true, whilewindow.foo === undefined
will be false (what you want).要测试常规变量是否存在,我认为最好的选择是将类型与未定义的类型进行比较,例如:
To test if a regular variable exists, I'd say your best bet is to compare the type to undefined, something like:
就我个人而言,如果有更简单的解决方案,我会尽量避免使用 try/catch 语句。
就您而言,JS 和其他所有语言都提供了一种更简单的方法来查看变量是否已定义。
或者如果变量是使用 var x 定义的:
Personally, I try to avoid using try/catch statements if there is a simpler solution.
In your case, JS and every other language provides an easier way to see if a variable is defined.
or if the variable was defined using var x:
在这种情况下我不会使用 try/catch 。如果它抱怨变量未定义,我会查找错误所在并修复它。
I wouldn't use try/catch in that circumstance. If it complained that a variable was undefined I'd look for where the bug was and fix it.
通常,异常用于通知应用程序程序员所做的假设不满足。例如 - 网络连接不起作用、文件不存在、安全性不允许某些操作等。
如果您知道某些变量可能未定义,那么您不应该使用异常,而是在 if 中处理该异常。或者遵循一种策略,尽可能地拥有有意义的目标或价值。
Generally, exceptions serve to notify the application that the assumption made by programmer was not satisfied. For example - network connection didn't work, file did not exist, security did not allow something, etc.
If you are aware of the fact that some variable may be undefined, then you should not use exceptions, rather handle that in an if. Or follow a strategy to have meaningful object or value whenever possible.
使用 if 语句检查变量是否已定义
实际上,try catch 是测试变量是否未定义的一种非常低效的方法。最好的方法是检查变量是否在 if 语句中定义。
Check the variable is defined using an if statement
Actually try catch is a very ineffecient way of testing if a variable is undefined. The best way is to check if the variable is defined in an if statement.