Javascript检测未定义的变量或对象属性

俺之前也写过一篇文章关于js检测数据类型的,详情见js中检查数据类型最佳实践

今天俺再跟大家介绍一下如何用js检测未定义的对象属性或变量。

完整版

if (typeof something === "undefined") {
    alert("something is undefined");
}

如果想要判断一个对象的属性,你可以这样判断:

if (typeof my_obj.someproperties === "undefined"){
    console.log('the property is not available...'); // print into console
}

缩写版

上面的代码也可以被简写,作用一样。

if (!variable){
    //do it if variable is Undefined
}
或
if (variable){
    //do it if variable is Defined
}
(0)
上一篇 2019年8月12日 下午5:42
下一篇 2019年8月12日 下午6:46

相关推荐

发表回复

登录后才能评论