我如何在 AutoHotkey 中找到关联数组的长度?

How do I find the length of an associative array in AutoHotkey?

如果使用length() function on an associative array,则会return在"largest index"内使用数组。因此,如果您有任何不是整数的键,length() 将不会 return 数组中元素的实际数量。 (这也可能由于其他原因而发生。)

是否有更有用的 length() 版本来查找关联数组的长度?

或者我是否需要实际循环并计算每个元素?如果事先不知道所有可能的密钥,我不确定该怎么做。

如果您有平面数组,那么 Array.MaxIndex() 将 return 索引中的最大整数。然而,这并不总是最好的,因为 AutoHotKey 将允许您拥有第一个索引不是 1 的数组,因此 MaxIndex() 可能会产生误导。

更糟糕的是,如果您的对象是一个关联哈希表,其中索引可能包含字符串,那么 MaxIndex() 将 return 为 null。

所以最好数一数。

DesiredDroids := object()
DesiredDroids["C3P0"] := "Gold"
DesiredDroids["R2D2"] := "Blue&White"
count :=0
for key, value in DesiredDroids
    count++
MsgBox, % "We're looking for " . count . " droid" . ( count=1 ? "" : "s" ) . "."

输出

We're looking for 2 droids.