3

我不了解函数中的数组,但是您如何找到数组中给出的匹配项?例如:

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

我怎样才能让它只显示数组中的苹果数量?

4

6 回答 6

4

简单地说,你可以这样做:

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
于 2012-04-07T03:04:45.230 回答
4

根据数组中有多少项目,以及您想要搜索不同项目的频率,每次您想要计算事物时,让 for 循环遍历整个数组可能会非常昂贵(如果您做了其他两个答案的建议)。您可能希望有一个 count 函数只遍历数组一次,并返回一个counters 列表,而不是单个数字:

function countItems( arr:Array ) : Object {
    var counts : Object = {};

    for each ( var item : String in arr ) {
        if (counts.hasOwnProperty(item)) counts[item]++;
        else counts[item] = 1;
    }
    return counts;
}

var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
var counts : Object = countItems(fruit);

trace (counts["apples"]);  // => 2
trace (counts["oranges"]); // => 2
trace (counts["grapes"]);  // => 2
于 2012-04-07T07:24:37.237 回答
1
function countOccurrences( haystack, needle ){
    var index : int = -1;
    var counter : int = -1;
    do{
        counter++;
        index = haystack.indexOf( needle, index + 1 );
    }while( index >= 0 );
    return counter;
}

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

trace( countOccurrences( fruit, "apples" ) ); //outputs '2'
于 2012-04-09T08:26:52.417 回答
1
var stringToSearch:String = "apples";
var pattern:RegExp = new RegExp(/\b\b/.source+stringToSearch, "g");
var matches:Array = fruit.toString().match(pattern);
//
trace(matches.length);

免责声明:如果您的数组中有很多元素(例如fruit.length>1000),请不要使用它:它很紧凑,但它可能比此处发布的任何其他解决方案都慢。要指出的另一件事是,在这里我假设您的“匹配项”是“字符串”。

于 2012-04-09T08:34:33.140 回答
0

尝试类似的东西

private function makeFilter(filterValue:String):Function {
   var fn:Function = function (obj:Object, index:int=0, arr:Array=[]):Boolean {
     if (String(obj)==filterValue) {
        return true;
     }
     return false;
   }
   return fn;
}

//somewhere else:
var filterFunction:Function = makeFilter('apples');
var appleCount:int = fruit.filter(filterFunction).length;

仅供参考,有关此方法的更多信息:http ://www.gasi.ch/blog/functional-actionscript-1/

于 2012-04-07T01:40:08.183 回答
0

var matches = 0
var arrayMatcher = (array1, array2) => {
    for (let i = 0; i <= array1 - 1; i++) {
        var myFirstItem = array1[i];
        for (a = 0; a <= array2.length - 1; a++) {
            var mySecondItem = array2[a];
            if (mySecondItem === myFirstItem) {
                matches += 1;
            }
        }
    }
    return matches;
}

我用它来查找患者症状列表与某种疾病的常见症状列表中的匹配项,它对我有用。你可以试一试!:)

于 2021-08-05T10:41:14.023 回答