我被警告说这篇文章可能过于主观,但我才编程几周,所以我想知道。
到目前为止,我一直在我的 JS 中使用 try/catch 语句来防止在运行函数时 undefined variable 的情况下抛出错误,但这是唯一有效的方法吗?
最佳答案
如果您在浏览器中,您可以使用 window.foo
测试全局变量。例如:
if (window.foo === undefined)
console.log("foo is not defined");
如果我正在阅读代码,我宁愿阅读此代码也不愿阅读 try { foo } catch { … }
。
另外,请注意三等号:这是必要的,因为如果 window.foo
为 null
,则 window.foo == undefined
将为 true,而 window.foo === undefined
将为 false(您想要的)。
关于javascript - 如果变量未定义,try/catch(其中一种)是防止错误发生的最佳方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6950797/