首页 > 解决方案 > Autohotkey:查找列表(对象)中的匹配数

问题描述

我需要在列表中找到匹配的数量。现在我可以使用笨拙的方式达到目的,如下所示:

aBlocks := ["A", "B", "C", "B"]
For key, value in aBlocks
{
    a = 0
    if (value == "B")
    {
        a += 1
    }
}
msgbox, %a% 

我想知道是否有任何现成的功能,例如object.count("B")[这个不起作用,因为它只返回对象中所有值的计数]。

标签: autohotkey

解决方案


不,不存在这样的方法(或函数或命令)。
在我看来,你所做的一切都很好。

您可以自己创建该方法:

MyArray := [1, 1, 2, 3, 4, 1]
MyArray2 := ["hello", "hello", "cool", "array"]
MyObj := {color: "red"
        , mileage: 86959
        , model: "ford"
        , price: "$200"
        , notes: "doesn't start"}
        
MsgBox, % MyArray.CountMatches(1)
MsgBox, % MyArray2.CountMatches("hello")
MsgBox, % MyObj.CountMatches("NoSuchValue")


Array(params*)
{
    return Object(params*)
}

Object(params*)
{
    return (params, params.base := CustomMethods)
}

class CustomMethods
{
    CountMatches(needle)
    {
        for each, value in this
            if(value == needle)
                i++
        return i ? i : 0
    }
}

虽然可能有点先进。自定义函数而不是方法肯定会更简单。不过,方法看起来不错。
如果您愿意,我可以稍后解释/评论该代码,现在没有时间。就这么快写了。


推荐阅读