Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript对象检查属性是否存在_Javascript - Fatal编程技术网

Javascript对象检查属性是否存在

Javascript对象检查属性是否存在,javascript,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 u

我有一个名为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

哪里出错了?

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

if (file && file.xhr && file.xhr.response) {
    // your logic...
}
代码示例:

var a={
b:{
d:‘d’
}
};
var resultC=a&&a.b&&a.b.c?“存在':'缺少';
控制台日志('a.b.c',结果);
var resultD=a&&a.b&&a.b.d.“存在':'缺少';

控制台日志('a.b.d',结果)您可以使用以下方法检查对象属性是否存在:

if (file && file.xhr && file.xhr.response) {
    // your logic...
}
代码示例:

var a={
b:{
d:‘d’
}
};
var resultC=a&&a.b&&a.b.c?“存在':'缺少';
控制台日志('a.b.c',结果);
var resultD=a&&a.b&&a.b.d.“存在':'缺少';

控制台日志('a.b.d',结果)
当它抛出
无法读取未定义的
属性“response”时,可以使用
if(typeof file.xhr!=“undefined”)

之类的东西。这并不意味着
response
不存在,而是它的父级不存在,在您的情况下,
xhr
。可能重复的错误表示,
response
未定义,但您在问题中输入的代码根本不使用
response
。问题不在您共享的代码中。当对象抛出
无法读取未定义的属性“response”时,您可以检查对象是否写入了属性。这并不意味着
response
不存在,而是意味着它的父级不存在,在您的情况下,
xhr
。可能重复的错误表示,
response
未定义,但您在问题中输入的代码根本不使用
response
。问题不在您共享的代码中。您可以检查对象是否写入了属性