我必须检查某个对象是否未定义,但是当我这样做时
typeof myUnexistingObject.myUnexistingValue == 'undefined'
我收到此错误
Uncaught ReferenceError: myUnexistingObject is not defined
那么,我该如何检查未定义的对象或属性?
答案 0 :(得分:2)
在使用之前,您必须检查每个可能定义的属性:
function checkUnexistingObject(myUnexistingObject) {
if (myUnexistingObject !== undefined) {
if (myUnexistingObject.otherObject !== undefined) {
console.log("All is well");
}
}
}
checkUnexistingObject({});
checkUnexistingObject({otherObject: "hey"});