为什么我在TypeScript中的伪字典似乎只存储关键字串?



以Ryan Cavanaugh的公认答案为精神,我不允许链接,他提出了这样的结构:

var map: { [email: string]: Customer; } = { };

模拟Customer的字典,其中字符串键打算是电子邮件地址,我尝试实现SelectionOtherInputDescriptor的类似伪字典1:

export class SelectionOtherInputDescriptor {
    constructor(public selectionName: string, public otherKey: any, public otherInputElementId: string) { }
}
export class SelectionOtherInputHelper {
    selectionsWithOther: { [selectionKey: string]: SelectionOtherInputDescriptor; } = {};
    getAllSelectionOthers() {
        var things = $("[" + ATT_SELECTION_OTHER_FOR + "]");           
        for (var i = 0; i < things.length; i++) {         
            var selectionName = $(things[i]).attr(ATT_SELECTION_OTHER_FOR);
            var desc = new SelectionOtherInputDescriptor(selectionName, 0, $(things[i]).attr("id"));
            this.selectionsWithOther[selectionName] = desc;
        };
        for (var i in this.selectionsWithOther) {
            window.console.log(i);
        }
    };
}

然而,我的变量selectionsWithOther似乎总是只包含三个字符串(在具有三个选择和其他元素的测试页面中),即selectionKey值。

1描述当用户在选择元素上选择Other时捕获实际值的输入。

这只是跟踪索引字符串(您的selectionKey):

for (var i in this.selectionsWithOther) {
    window.console.log(i);
}
要跟踪映射到该索引的值,您需要:
for (var i in this.selectionsWithOther) {
    window.console.log(this.selectionsWithOther[i]); // Will trace 'Object'
    window.console.log(this.selectionsWithOther[i].selectionName); // Should trace the value of the property on that object
}

关于JS中关联数组的更多信息:http://www.quirksmode.org/js/associative.html

最新更新