【发布时间】:2022-01-04 12:08:44
【问题描述】:
您好,我正在学习 Angular,并尝试按照 YouTube 上的 Note Mates 教程进行操作,我几乎完成了,但这对我不起作用。我应该按相关性进行排序,我在这里有这段代码,我得到的 Element 隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引 noteCountObj[noteId] 的“对象”类型错误。
sortByRelevancy(searchResults: Note[]) {
// This method will calculate the relevancy of a note based on the number of times it appears in
// the search results
let noteCountObj: Object = {}; // format - key:value => NoteId:number (note object id : count)
searchResults.forEach(note => {
let noteId = this.service.getId(note);
if (noteCountObj[noteId]) {
noteCountObj[noteId] += 1;
} else {
noteCountObj[noteId] = 1;
}
});
this.filteredNotes = this.filteredNotes.sort((a: Note, b: Note) => {
let aId = this.service.getId(a);
let bId = this.service.getId(b);
let aCount = noteCountObj[aId];
let bCount = noteCountObj[bId];
return bCount - aCount;
});
}
我怎样才能做到这一点? 谢谢你的帮助。
【问题讨论】:
-
noteId的类型是什么?这是字符串还是数字?
标签: angular typescript error-handling