如何区分未声明的变量和已声明但未分配任何值的变量? [英] How to distinguish between a variable that is not declared and a varrable that is declared but not be assigned any value?

查看:101
本文介绍了如何区分未声明的变量和已声明但未分配任何值的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在两种情况下,变量的类型均为未定义". 但是未声明的变量将引发异常.

Both scenario, the typeof the variable will be "undefined". But undeclared variable will raise a exception.

有一种简单的方法可以解决这个问题吗?

Is there a easy way to handle this?

推荐答案

您可以在

You may find the question (and my answer) in How to check if a variable or object is undefined? relevant. In general, I view any access to an "undeclared variable" a programming error.

但是,通过检测ReferenceError异常,可以*仅**检测到这种特殊情况.但是, yuck,yuck,yuck!.请记住,变量声明是一个静态词汇构造,它忽略了带有全局对象的属性变量的怪癖.

However, this particular case can *only** be detected with the use of detecting for a ReferenceError exception. But, yuck, yuck, yuck! Remember variable declarations are a static lexical construct, ignoring the quirks with property-variables of the global object.

ReferenceError(现在为严格")存在是有原因的,我怀疑这是X-Y问题.我什至不建议为此目的使用typeof:修复代码:-)

ReferenceError, and now "strict", exist for a reason and I suspect this is an X-Y problem. I do not even recommend the use of typeof for this purpose: fix the code :-)

快乐的编码.

*已经指出,"variable" in window也将[并且仅]适用于全局变量"(它们实际上只是属性,不需要在所有情况下都限定).

*It has been pointed out that "variable" in window will also [and only] work for global "variables" (they are really just properties that don't need be qualified in all contexts).

这篇关于如何区分未声明的变量和已声明但未分配任何值的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆