Javascript对象检查属性是否存在

时间:2017-11-07 11:13:05

标签: javascript

我有一个名为 file 的javascript对象,我正在尝试检查此对象是否包含file.xhr.response属性。我试过这样的..

if (file.xhr.response) {
    console.log(Exists);
} else {
    console.log(Missing);
}

file.xhr.response 存在但是如果不存在则会产生错误...

Uncaught TypeError: Cannot read property 'response' of undefined

我哪里错了?

3 个答案:

答案 0 :(得分:3)

您可以使用以下方法检查对象属性是否存在:

if (file && file.xhr && file.xhr.response) {
    // your logic...
}

代码示例:

var a = {
  b: {
    d: 'd'
  }
};

var resultC = a && a.b && a.b.c ? 'Exists' : 'Missing';
console.log('a.b.c', resultC);

var resultD = a && a.b && a.b.d ? 'Exists' : 'Missing';
console.log('a.b.d', resultD);

答案 1 :(得分:-1)

使用try / catch语句,如果错误被触发,你可以在catch块中处理它。

答案 2 :(得分:-1)

您可以使用if(typeof file.xhr!="undefined")

之类的内容
相关问题