【问题标题】:Why does my pseudo-dictionary in TypeScript seem to only store the key strings?为什么我在 TypeScript 中的伪字典似乎只存储键字符串?
【发布时间】:2013-02-19 20:22:34
【问题描述】:

本着 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 描述当用户在选择元素上选择“其他”时捕获实际值的输入。

【问题讨论】:

  • 如果您也发布 JS 输出,可能更容易诊断。

标签: javascript asp.net-mvc typescript


【解决方案1】:

这只是跟踪索引字符串(你的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

【讨论】:

  • 啊哈,谢谢。我有这样的概念,即“foreach”迭代整个对象,就像在 C# 中一样。
猜你喜欢
  • 2020-08-04
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 1970-01-01
  • 2018-04-19
  • 2023-01-11
相关资源
最近更新 更多