如何检查对象是否未定义(javascript)?

时间:2017-03-12 23:51:20

标签: javascript undefined javascript-objects

我必须检查某个对象是否未定义,但是当我这样做时

typeof myUnexistingObject.myUnexistingValue == 'undefined'

我收到此错误

Uncaught ReferenceError: myUnexistingObject is not defined

那么,我该如何检查未定义的对象或属性?

1 个答案:

答案 0 :(得分:2)

在使用之前,您必须检查每个可能定义的属性:



function checkUnexistingObject(myUnexistingObject) {
  if (myUnexistingObject !== undefined) {
    if (myUnexistingObject.otherObject !== undefined) {
      console.log("All is well");
    }
  }
}
checkUnexistingObject({});
checkUnexistingObject({otherObject: "hey"});