我不理解函数中的数组,但是如何找到数组中给出的匹配项?例如:
var fruit:Array = ["apples", "oranges", "grapes", "oranges", "apples", "grapes"];
我怎样才能让它只显示数组中的苹果数量?
答案 0 :(得分: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
答案 1 :(得分:4)
根据数组中的项目数量以及搜索不同项目的频率,每次想要计算内容时,对整个数组进行for循环迭代会非常昂贵(这会如果你做了其他两个答案建议的话就会发生)。您可能希望只有一次迭代数组的计数函数,并返回计数器列表,而不是单个数字:
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
答案 2 :(得分: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'
答案 3 :(得分: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&gt; 1000),请不要使用此选项:它非常紧凑但可能比此处发布的任何其他解决方案都慢。另外需要指出的是,我假设你的“匹配项目”是“字符串”。
答案 4 :(得分: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/
答案 5 :(得分: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;
}
我用它在患者症状列表中查找与某种疾病常见症状列表相匹配的结果,它对我有用。你可以试试看! :)