while(parentId){
ancestors.push(parentId);
parent = Comments.findOne(parentId);
if(typeof parent.parentCommentId === "undefined"){
break;
} else {
parentId = parent.parentCommentId;
console.log(parentId);
}
}
我希望这段代码推送数组中的所有parentCommentId,直到顶部的注释文档top.But没有字段parentCommentId为止。
我在控制台中遇到这个错误,typeof Cannot read property 'parentCommentId' of undefined {stack: (...), message: "Cannot read property 'parentCommentId' of undefined"}
hasOwnProperty不起作用,我如何检查属性
发布于 2014-12-04 00:37:09
无法读取未定义的属性“”parentCommentId“”
这意味着拥有您试图访问的属性的对象是未定义的,因此问题不在于该属性。
在您的示例中,Comments.findOne
似乎没有找到具有该id的任何内容,因此parent
对象是未定义的。
如您所知,检查对象中是否存在属性的另一种方法是:
if (parent.parentCommentId) {
}
发布于 2014-12-04 02:04:56
如果没有给定ID的结果,Comments.findOne(parentId)可以返回undefined。
parent = Comments.findOne(parentId); //parent can be undefined
if (!parent) {
//parent is undefined
} else {
//parent found
}
上面的代码与:
parent = Comments.findOne(parentId); //parent can be undefined
if (typeof parent === "undefined"){
//parent is undefined
} else {
//parent found
}
因此,答案是:您需要检查是否定义了parent。如果是,则可以访问其属性。
https://stackoverflow.com/questions/27276172
复制相似问题