在TypeScript可索引接口中访问index



我使用索引类型在typescript中创建了一个"字典",并试图将其用作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: “ + ??);
}

这是你的代码的一个完整的工作示例…基本上你所有的接口都是正确的,你只需要调整环路中的那个位,就像你用???指示的那样。

关键是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);

实际上,设置是ID。需要索引的值,可以使用[id]

了解更多关于for/in的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

最新更新