我使用索引类型在typescript中创建了一个“Dictionary”,并尝试将其用作for in语句中的数组。我能够毫无问题地获得值,但无法弄清楚我如何访问索引(参见for循环中的??)。
export interface Settings {
dictionary : IDictionary[];
}
export interface IDictionary{
[index: number]: string;
}
// To be used like this
for (var setting in Settings.dictionary)
{
console.log(“Setting is: “ + setting + “ for id: “ + ??);
}
答案 0 :(得分:1)
实际上,设置是ID。使用[id]
索引所需的值详细了解for / in:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
答案 1 :(得分:1)
以下是您的代码的完整工作示例...基本上您的所有界面都是正确的,您只需在循环中调整该位,就像您使用???
所示。
关键是setting
要获取该值,请使用settings.dictionary[setting]
以下是完整代码:
export interface Settings {
dictionary : IDictionary[];
}
export interface IDictionary{
[index: number]: string;
}
function logSettings(settings: Settings) {
for (var setting in settings.dictionary) {
console.log('Setting is: ' + settings.dictionary[setting] +
' for id: ' + setting);
}
}
var settings: Settings = {
dictionary: []
};
settings.dictionary[0] = 'A';
settings.dictionary[1] = 'B';
logSettings(settings);