arrays - 计算数组中的出现次数

标签 arrays actionscript-3 actionscript find-occurrences

我想计算ActionScript 3.0中数组中的出现次数。说我有

var item:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];

如何显示匹配字符串的数量?例如,结果:苹果= 2,橘子= 2,依此类推。

我从另一个类似的问题得到了这段代码:
    private function getCount(fruitArray:Array, fruitName:String):int {
    var count:int=0;
    for (var i:int=0; i<fruitArray.length; i++) {
        if(fruitArray[i].toLowerCase()==fruitName.toLowerCase()) {
            count++;
        }
    }
    return count;
}

var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
var appleCount=getCount(fruit, "apples"); //returns 2
var grapeCount=getCount(fruit, "grapes"); //returns 2
var orangeCount=getCount(fruit, "oranges"); //returns 2

在此代码中,如果您想获得说“苹果”的数量。您需要为每个项目设置变量(var appleCount = getCount(fruit,“apples”))。但是,如果您有成千上万的水果名称,就不可能为每个水果写下新的变量。

我是AS3的新手,请原谅我。我想理解代码,请在代码中加入清晰的注释。

最佳答案

    var item:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];

    //write the count number of occurrences of each string into the map {fruitName:count}
    var fruit:String;
    var map:Object = {}; //create the empty object, that will hold the values of counters for each fruit, for example map["apples"] will holds the counter for "apples"

    //iterate for each string in the array, and increase occurrence counter for this string by 1 
    for each(fruit in item)
    {
        //first encounter of fruit name, assign counter to 1
        if(!map[fruit])
            map[fruit] = 1;
        //next encounter of fruit name, just increment the counter by 1
        else
            map[fruit]++;
    }

    //iterate by the map properties to trace the results 
    for(fruit in map)
    {
        trace(fruit, "=", map[fruit]);
    }

输出:
apples = 2
grapes = 2
oranges = 2

关于arrays - 计算数组中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16647556/

相关文章:

css - 将外部 css 应用于加载到 flash actionscript 中的 xml

actionscript-3 - 类型错误 : Error #2007: Parameter child must be non-null

ios - 将Adobe Air应用程序上传到iTunes Connect时,ITMS-90086“缺少64位支持”错误

javascript - 将javascript字符串转换为数组

python - np.concatenate()2D数组而不是1D

arrays - O(nlog(n))中的下一个更大的最小元素

javascript - 访问数组中的对象

actionscript-3 - AS3- 是否可以从字符串中调用变量?

flash - 最佳 Flash 上传小工具

apache-flex - 通过URLRequest上传字节数组