Javascript 如果函数的类型等于undefined,如何返回false?

Javascript 如果函数的类型等于undefined,如何返回false?,javascript,Javascript,在JavaScript中,如果对象或函数的类型未定义,是否有方法显示消息或返回false?似乎如果对象或函数不存在,则无法在屏幕上显示错误消息,而是错误出现在Web控制台中。这应该有帮助: if (typeof foo === "undefined") { // foo is undefined } 或者(请参见),您也可以使用: if (foo === void(0)) { // foo is undefined } 如果(foo===undefined),则不应使用if(

在JavaScript中,如果对象或函数的类型未定义,是否有方法显示消息或返回false?似乎如果对象或函数不存在,则无法在屏幕上显示错误消息,而是错误出现在Web控制台中。

这应该有帮助:

if (typeof foo === "undefined") {
    // foo is undefined
}
或者(请参见),您也可以使用:

if (foo === void(0)) {
    // foo is undefined
}
如果(foo===undefined),则不应使用
if(foo===undefined)
,因为(as),全局属性
undefined
在某些浏览器中可能具有非默认值(从JavaScript 1.8.5-Firefox 4开始,它是一个只读属性)。

这将有助于:

if (typeof foo === "undefined") {
    // foo is undefined
}
或者(请参见),您也可以使用:

if (foo === void(0)) {
    // foo is undefined
}

您不应该使用
if(foo===undefined)
,因为(as)全局属性
undefined
在某些浏览器中可能有一个非默认值(从JavaScript 1.8.5-Firefox 4开始,它是一个只读属性)。

typeof
操作符将为您提供变量的类型,或者字符串
“undefined”
如果未定义变量

if (typeof myvar === 'undefined') {
    // it's not defined
}
或者,如果需要布尔值:

var itsDefined = (typeof myvar !== 'undefined');
这名义上比测试更安全:

if (var === undefined)

因为在某些浏览器上,
未定义的
可能会被覆盖。

类型的运算符将为您提供变量的类型,如果变量未定义,则字符串将为您提供
“未定义的”

if (typeof myvar === 'undefined') {
    // it's not defined
}
或者,如果需要布尔值:

var itsDefined = (typeof myvar !== 'undefined');
这名义上比测试更安全:

if (var === undefined)

因为在某些浏览器上,
未定义的
可能会被覆盖。

在访问变量的任何方法或孙子属性之前,您应该检查是否使用
类型的
检查(
类型的x==“未定义的”
)或尝试捕获来定义它:

try{
    x.method();
}catch(e){
    /*You could check the error message to see if the exception was thrown because x is undefined.*/
}

在访问变量的任何方法或子对象属性之前,应检查是否使用
typeof
检查(
typeof x==“undefined”
)或try-catch定义该变量:

try{
    x.method();
}catch(e){
    /*You could check the error message to see if the exception was thrown because x is undefined.*/
}
(强制性回答,包括过度使用第三方库)

有趣的是,它使用的方法与此处提供的其他答案略有不同:

_.isUndefined = function(obj) {
    return obj === void 0;
  };
)
(强制性回答,包括过度使用第三方库)

有趣的是,它使用的方法与此处提供的其他答案略有不同:

_.isUndefined = function(obj) {
    return obj === void 0;
  };
)

美好的这与
返回obj===未定义相同除非它不受为
未定义的
指定非默认值的代码的影响。这可能比先进行
typeof
查找,然后进行字符串比较要高效得多。很好。这与
返回obj===未定义相同除非它不受为
未定义的
指定非默认值的代码的影响。它可能比先进行
typeof
查找,然后进行字符串比较要高效得多。对于后者,您可以使用
void(0)
来避免
未定义的
被覆盖。请参阅。关于后者,您可以使用
void(0)
来隔离
未定义的
被覆盖。看见