如何检查JavaScript中的对象属性是否未定义?


当前回答

if (somevariable == undefined) {
  alert('the variable is not defined!');
}

您也可以将其转换为函数,如下所示:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}

其他回答

如果使用的是Angular:

angular.isUndefined(obj)
angular.isUndefined(obj.prop)

Undercore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 
if (somevariable == undefined) {
  alert('the variable is not defined!');
}

您也可以将其转换为函数,如下所示:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}
function isUnset(inp) {
  return (typeof inp === 'undefined')
}

如果变量已设置,则返回false;如果未定义,则返回true。

然后使用:

if (isUnset(var)) {
  // initialize variable here
}
if ( typeof( something ) == "undefined") 

这对我有用,而其他人没有。

ECMAScript 10引入了一个新特性——可选链接,只有当对象定义为如下时,才可以使用该特性来使用对象的属性:

const userPhone = user?.contactDetails?.phone;

只有在定义了user和contactDetails时,它才会引用phone属性。

裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining