2013-05-20 114 views
2

我想在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是全新的,所以原谅我。请在代码中包含明确的注释,因为我想了解代码。

回答

10
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 
+0

三江源! :)像一个魅力工作。但是,你能解释一下每个代码的作用和方式吗? (对不起,我是一个新手,并试图学习) – rohan

相关问题