我有一个名为comment的对象,该对象具有description属性和editedDescription Array。每当用户编辑描述时,新的描述将被推入editedDescription数组。此数组用于维护已编辑描述的历史记录。 以下是我的评论对象:
export interface Comment {
userName: String,
userImage: String,
description: String,
upvote : Number,
downvote : Number,
createdDate: Date,
replies: [
{
userName: String,
userImage: String,
description: String,
upvote : Number,
downvote : Number,
createdDate: Date
}
],
editedDescription: [
{
Description: String,
editedDate: Date
}
]
}
为了输出editedDescription数组的最后一个元素,我尝试了:
{{ comment?.editedDescription[editedDescription?.length-1]?.Description}}
我遇到以下错误-'无法读取未定义的属性'-1' 我已经使用了安全的导航操作符来检查数组是否存在,但是即时通讯无法读取未定义的-1
这是我的部分失败的代码
<div *ngIf="comment?.editedDescription?.length == 0 ; else edited_comment">
<p> {{ comment?.description }}</p>
</div>
<ng-template #edited_comment>
<p> {{ comment?.editedDescription[editedDescription?.length-1]?.Description}}</p>
</ng-template>
* ng如果条件检查是否editedDescription数组中没有数据,请使用description属性,否则请使用editedDescription数组的最后一个元素。
答案 0 :(得分:1)
我认为需要遵循以下条件,因为目前您不尝试通过听起来像是存储的comment
访问数组。
{{ comment?.editedDescription[comment.editedDescription.length -1 ]?.Description}}
寻找长度时,您仍然需要访问注释。当您对安全操作员满意时,请把它们放回去。下面显示了您尝试过的简化示例。
const obj = { hello: [1, 2, 3] };
console.log(obj.hello[obj.hello.length - 1]); // last element, expected 3
// console.log(obj.hello[hello.length - 1]) // This is like what you have done.