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


当前回答

我们ES6可以与!!将所有值转换为布尔值。使用此选项,所有假值都将变为假。

第一种解决方案

if (!(!!variable)) {
    // Code
}

第二种解决方案

if (!variable) {
    // Code
}

其他回答

如果使用的是Angular:

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

Undercore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 

检查是否存在密钥的一种简单方法是:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true
if (somevariable == undefined) {
  alert('the variable is not defined!');
}

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

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

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

const userPhone = user?.contactDetails?.phone;

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

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

Use:

要检查属性是否未定义,请执行以下操作:

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

要检查属性是否未定义,请执行以下操作:

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