【发布时间】:2019-07-04 09:14:10
【问题描述】:
更新:我尝试像这样记录:@Kobe 建议的console.log(JSON.stringify(this.idTitleDict))。这显示了空的花括号……关于这本字典的所有代码(声明,填充它)都发布在下面。我首先调用this.getTemplates() 来填充字典,然后下一行我想遍历它。当我将字典传递给JSON.stringify() 后将它记录到控制台时,它似乎是空的。
在我的 Angular 应用程序中组件的 ngOnInit 方法中,我遍历字典以获取第一个键,然后跳出循环。但它似乎没有被迭代。
字典看起来像这样:
{
1: "title",
2: "title",
3: "title",
4: "title",
5: "title",
6: "title"
}
我试过了:
const keys = Object.keys(this.idTitleDict);
for (const key in keys) {
if (this.idTitleDict.hasOwnProperty(key)) {
console.log(key);
this.showContent(key);
break;
}
}
还有:
for (const key in this.idTitleDict) {
if (this.idTitleDict.hasOwnProperty(key)) {
console.log(key);
this.showContent(key);
break;
}
}
还有:
for (const key in Object.keys(this.idTitleDict)) {
if (this.idTitleDict.hasOwnProperty(key)) {
console.log(key);
this.showContent(key);
break;
}
}
没有任何东西被记录到控制台并且this.showContent() 没有被执行。自从我检查了字典后,我确定字典已被填充。在另一个函数中,我遍历另一个字典,这没有问题:
getTemplates() {
this.apiService.getTemplates().subscribe(
(data: any) => {
for (const key in data) {
if (data.hasOwnProperty(key)) {
this.idTitleDict[key] = data[key].title;
}
}
}
);
}
完整的 ngOnInit 方法:
ngOnInit() {
this.getTemplates();
const keys = Object.keys(this.idTitleDict);
console.log(this.idTitleDict); // this shows the dictionary is populated as shown in the dictionary at the top of this post
for (const key in Object.keys(this.idTitleDict)) {
if (this.idTitleDict.hasOwnProperty(key)) {
console.log(key);
this.showContent(key);
break;
}
}
}
字典声明:
idTitleDict: { [id: string]: string; } = {};
用这个方法填写:
getTemplates() {
this.apiService.getTemplates().subscribe(
(data: any) => {
for (const key in data) {
if (data.hasOwnProperty(key)) {
this.idTitleDict[key] = data[key].title;
}
}
}
);
}
我可能错过了一些东西,但我束手无策。
【问题讨论】:
-
要迭代的列表在哪里?
-
@Ntwobike 我想遍历前 3 个代码块中显示的字典,我将更新显示字典外观的帖子
-
初始化后
keys数组包含什么?仅作记录 -hasProperty的if是多余的,因为您已经在迭代现有的键... -
另外,这个 sn-p 应该足够了:
js Object.keys(this.idTitleDict).forEach(this.showContent) -
@devnull69 不正确
标签: javascript angular typescript for-loop