解析为数字的关联数组键 return 无结果

Assoicative Array keys that resolve to numbers return no results

如果我遍历字符串数组,并将每个字符串用作关联数组的键,作为数字字符串表示的键不能"find"其关联值:

KeyArray := Array("AAA", "777")
AssocArray := {"AAA":{"Item1":"Item1Value", "Item2":"Item2Value"} 
              ,"777":{"Item1":"Item1Value", "Item2":"Item2Value"}}

Loop % KeyArray.Length() {
    aKey := KeyArray[A_Index]
    aValue := AssocArray[aKey]
    sResult := aKey . ": " . aValue["Item1"] . "`t" . aValue["Item2"]
    ToolTip, % sResult
    OutputDebug % "[AHK] sResult: " . sResult . " " 
    Sleep 5000
}

但是,如果我使用 For 循环来迭代键:

For aKey, aValue In AssocArray {
    sResult := aKey . ": " . aValue["Item1"] . "`t" . aValue["Item2"]
    ToolTip, % sResult
    OutputDebug % "[AHK] sResult: " . sResult . " " 
    Sleep 5000
}

然后“777”被识别为键,并​​且它的值被正确返回 或者,如果我在 KeyArray 和 AssocArray 中删除“777”中的引号,那么两个循环都会找到正确的值。

现在回答问题:
如何正确使用数字的字符串表示作为关联数组的键?

非常感谢!

这与内部类型强制和数字缓存有关。

换句话说,字符串“777”在 AssocArray[aKey] 中被强制转换为数字 777,因为任何表达式(在本例中为 aKey)如果计算结果为数字形式,则会生成一个数字,除非另有明确说明。

解决方法:

aValue := AssocArray[aKey ""]

通过上面的单行修改,你的第一段代码已经测试成功。


编辑

关于下面评论中的问题,这里有一些参考:

Caching
type coercion aka implicit type conversion

但是请注意,"implicit" and "explicit" are relative terms 在强制上下文中。