while(parentId){
ancestors.push(parentId);
parent = Comments.findOne(parentId);
if(typeof parent.parentCommentId === "undefined"){
break;
} else {
parentId = parent.parentCommentId;
console.log(parentId);
}
}
我希望此代码将数组中的所有parentCommentId推送到top。但是顶部注释文档没有字段parentCommentId。
我在控制台中遇到此错误
Cannot read property 'parentCommentId' of undefined {stack: (...), message: "Cannot read property 'parentCommentId' of undefined"}
typeof和hasOwnProperty不起作用,我该如何检查属性
答案 0 :(得分:0)
无法读取属性' parentCommentId'未定义的
这意味着拥有您尝试访问的属性的对象是未定义的,因此问题不在于属性。
在您的情况下,似乎Comments.findOne
没有找到任何带有该ID的内容,因此parent
对象未定义。
您也知道,检查对象中是否存在属性的另一种方法是:
if (parent.parentCommentId) {
}
答案 1 :(得分:0)
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
}
所以答案是:你需要检查是否定义了父级。如果是,那么您可以访问其属性。