哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
if (variable === undefined) {}
工作正常,只检查未定义。
其他回答
这些答案(除了Fred Gandt解决方案)要么不正确,要么不完整。
假设我需要我的variableName;携带一个未定义的值,因此它是以var variableName等方式声明的;这意味着它已经初始化;-如何检查是否已申报?
或者更好——我如何立即检查“Book1.chapter22.paragraph37”是否存在一次调用,但不会引起引用错误?
我们通过使用最强大的JasvaScript运算符in运算符来实现
"[variable||property]" in [context||root]
>> true||false
您需要运算符的类型。明确地:
if (typeof variable !== 'undefined') {
// the variable is defined
}
我很惊讶这还没有被提及。。。
以下是使用此['var_name']的一些其他变体
使用此方法的好处是,它可以在定义变量之前使用。
if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part
// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!
这取决于您是否只关心变量是否已定义,或者是否希望它具有有意义的值。
检查类型是否未定义将检查变量是否已定义。
==空或!==null将仅检查变量的值是否完全为null。
==空或!=null将检查该值是否未定义或为null。
if(value)将检查变量是否为undefined、null、0或空字符串。
为了使if条件正确工作,我们必须使用关键字let来创建变量。
let name = undefined;
if (name) {
alert('valid')
};