在JavaScript中,每当设置任何变量不确定时,是否有可能丢弃错误?
我发现JavaScript设置了一个等于未定义的变量,而不是丢弃错误会使调试变得更加困难,而且我从未发现它有帮助。例如:
var a = ["apple","banana","orange"]
var b = a[5]
将B设置为未定义,而不是丢弃错误。只有稍后使用B时,才会丢弃错误,从而更难看到错误的来源。
然后,我可以检查B的值:
if(b===undefined){
throw "variable undefined"
}
但是,每当我定义或更改任何变量的值时,我都不想这样做。
有什么方法可以使JavaScript在设置不确定的任何变量时自动丢失错误?
I find JavaScript setting a variable equal to undefined instead of throwing an error makes debugging far more difficult and I have never found it helpful. For example:
var a = ["apple","banana","orange"]
var b = a[5]
would set b to undefined instead of throwing an error. Only when b is later used would an error be thrown, making it harder to see the source of the error.
I could then check the value of b:
if(b===undefined){
throw "variable undefined"
}
but I wouldn't want to do this every time I define or change the value of any variable.
Is there any way to make JavaScript automatically throw an error whenever any variable is set to undefined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
特别是针对这种情况的,我已经准备了一个功能,该函数会采用对象和键/索引的arr,并返回目标值,或者在未定义的情况下默认值。您可以更改它以丢弃错误。
这只是意味着每当您想要对象值时,使用此语法:
gov(obj,[key1,key2])
而不是obj [key1] [key2] [key2]
。Specifically for this case, and others, I have prepared a function which takes an object and arr of keys/indexes and returns the targeted value, or default in case of undefined. You can change it to throw an error.
It just means that when ever you want object value, use this syntax:
gov(obj, [key1, key2])
instead ofobj[key1][key2]
.