0

如果我有一个类似的数组:

var myArray:Array = new Array("a","b","c","d","e","f","g","b");

如何搜索它以确定其中出现值的次数以及出现在哪些位置?我发现下面的代码很接近,但它只会返回第一次出现。

function findIndexInArray(value:Object, arr:Array):Number {
    for (var i:uint=0; i < arr.length; i++) {
        if (arr[i]==value) {
            return i;
        }
    }
    return NaN;
}

var myArray:Array = new Array("a","b","c","d","e","f","g","b");
trace(findIndexInArray("b", myArray));

// OUTPUT
// 1
4

2 回答 2

1

您可能会考虑返回存在搜索词的索引数组。例如:

var list:Array = ['a', 'b', 'b', 'c', 'd', 'e', 'f'];

function find(obj:Object, list:Array):Array
{
    var result:Array = [];
    for(var i:int = 0; i < list.length; i++)
    {
        if(list[i] = obj)
        {
            result.push(i);
        }
    }
    return result;
 }

 var search:Array = find('b', list);
 trace('b is found: ' + search.length + ' times at indices: ' + search); 
 // -- 'b is found: 2 times at indices [1, 2]

这样,您可以通过检查返回数组的长度来查看搜索词出现了多少次。

于 2013-03-19T17:39:09.133 回答
0

you could use join and regex to do the count

something like this:

// convert to one long string
var str:String = myArray.join("");

// regex find the letter and count result
var count:int = str.match(new RegExp(letter,"a")).length; 

haven't tested it, so the code might need a tweak, but this should be faster than looping through the array.


update

// convert to one long string
var str:String = myArray.join("");

var pos:Array = new Array();       
var n:int = -1;     

// loop through array and find all indexes
while ((n = str.indexOf(searchFor, n+1)) != -1) pos.push(n); 

just a warning though, this will break if any string in the array has more than one character

于 2013-03-19T17:51:50.550 回答