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


当前回答

回顾

许多给定的答案给出了错误的结果,因为它们没有区分对象属性不存在的情况和属性值未定义的情况。以下是最流行的解决方案的证明:

让obj={a: 666中,u: undefined//“u”属性的值为“undefined”//“x”属性不存在}console.log('>>>好结果:');console.log('A',obj中的“u”,obj的“x”);console.log('B',obj.hasOwnProperty(“u”),obj.hasOwnProperty(“x”));console.log('\n>>>坏结果:');console.log('C',obj.u==未定义,obj.x==未确定);console.log('D',obj.u==未定义,obj.x==未定义);console.log('E',obj[“u”]==未定义,obj'“x”]===未定义);console.log('F',obj[“u”]==未定义,obj'“x”]===未定义);console.log('G',!obj.u,!obj.x);console.log('H',对象类型u=='未定义',对象的类型x=='不定义');

其他回答

function isUnset(inp) {
  return (typeof inp === 'undefined')
}

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

然后使用:

if (isUnset(var)) {
  // initialize variable here
}

如果使用的是Angular:

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

Undercore.js:

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

“if(window.x){}”是错误安全的

很可能您想要if(window.x)。即使x尚未声明(var x;),该检查也是安全的-浏览器不会抛出错误。

示例:我想知道我的浏览器是否支持历史API

if (window.history) {
    history.call_some_function();
}

工作原理:

window是一个包含所有全局变量作为其成员的对象,尝试访问不存在的成员是合法的。如果x尚未声明或未设置,则window.x返回undefined。undefined在if()求值时导致false。

这可能是确定现有属性名称是否具有显式和预期值undefined的唯一显式形式;尽管如此,这是一种JavaScript类型。

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true \ false

仅当给定上下文的属性名存在(真实存在)并且其预期值未明确定义时,此表达式才会返回true。

不会出现假阳性,例如空字符串、空字符串、零、空数组等。这正是如此。检查,即确保属性名存在(否则将为假阳性),然后显式检查其值是否未定义,例如其字符串表示形式中的未定义JavaScript类型(字面上为“undefined”),因此==而不是==,因为无法进行进一步转换。只有满足这两个条件,这个表达式才会返回true。例如,如果属性名称不存在,则返回false。这是唯一正确的返回,因为不存在的财产不能有值,甚至不能有未定义的值。

例子:

containerObject = { propertyName: void "anything" }
>> Object { propertyName: undefined }

// Now the testing

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true

/* Which makes sure that nonexistent property will not return a false positive
 * unless it is previously defined  */

"foo" in containerObject && ""+containerObject["foo"] == "undefined";
>> false

也可以使用代理。它可以处理嵌套调用,但需要额外检查一次:

function resolveUnknownProps(obj, resolveKey) {
  const handler = {
    get(target, key) {
      if (
        target[key] !== null &&
        typeof target[key] === 'object'
      ) {
        return resolveUnknownProps(target[key], resolveKey);
      } else if (!target[key]) {
        return resolveUnknownProps({ [resolveKey]: true }, resolveKey);
      }

      return target[key];
    },
  };

  return new Proxy(obj, handler);
}

const user = {}

console.log(resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else); // { isUndefined: true }

因此,您将像这样使用它:

const { isUndefined } = resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else;
if (!isUndefined) {
  // Do something
}