更新:我尝试像这样记录:console.log(JSON.stringify(this.idTitleDict))
按照@Kobe 的建议。这显示了空的花括号……关于这个字典的所有代码(声明,填充它)都在下面发布。我首先调用 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;
}
}
}
);
}
我可能错过了什么,但我已经无计可施了。
最佳答案
如果你只想调用第一个键的方法,你为什么不像下面那样简单
const keys = Object.keys(this.idTitleDict);
if(keys.length){
this.showContent(keys[0]);
}
关于javascript - 为什么我不能遍历字典/键数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56884519/