AS3:多维数组中的indexOf()子数组

时间:2010-07-14 18:39:36

标签: actionscript-3

var asdf:Array = [ [1,1] ];
trace( asdf.indexOf( [1,1] ) ); // -1

为什么indexOf()找不到[1,1]数组?

3 个答案:

答案 0 :(得分:3)

这是我刚才写的一个小功能,效果很好。我包含了很多注释和一个示例搜索/函数来输出结果。

// set up a multidimensional array that contains some data
var myArray:Array = new Array();
myArray.push(["granola","people... are great"," 4 ","10"]);
myArray.push(["bill","orangutan","buster","keaton"]);
myArray.push(["steve","gates","24","yes, sometimes"]);
myArray.push(["help","dave","jobs","hal"]);

// here we set up some properties on the array object to hold our search string and our results
myArray.myTarget = "steve";
myArray.myResults = [];

// now we call the search
myArray.forEach(multiSearch);

// this is the function that does all the heavy lifting....
function multiSearch(element:*, index:int, array:Array)
{
    // see if we have a match in this array and pass back its index
    for(var i:* in element)
    {   
        if( element[i].indexOf( array.myTarget ) > -1 )
        {
            var tempArray:Array = array.myResults;
            tempArray.push([index,i]);
            array.myResults = tempArray;
        }
    }
}

// -------------------------------------------------------------------------------
// all the code below is OPTIONAL... it is just to show our results
// in the output window in Flash so you know it worked....
var printArray:Array = myArray.myResults;
for(var i:* in printArray)
{
    trace("TARGET FOUND @: "+printArray[i][0]+", "+printArray[i][1]+" = "+myArray[ printArray[i][0] ][ printArray[i][1] ]); 
}
// -------------------------------------------------------------------------------

答案 1 :(得分:1)

失败是因为当您执行[x,y]创建新数组时,adsf包含一个数组,indexOf搜索另一个数组。

尝试:

trace([1,1] == [1,1]);

您会看到它打印为false,因为数组是通过引用进行比较的。

一个快速indexOf功能,安排它以满足您的需求:

function isElmEquals(e1:*, e2:*):Boolean {
    return (e1==e2);
}

function isArrayEquals(a1:Array, a2:Array):Boolean {
    if (a1==a2)
        return true;

    if ((a1==null) || (a2==null)) {
        return false;
    }

    if (a1.length!=a2.length)
        return false;

    for (var i:int=0;i<a1.length;i++){
        if (!isElmEquals(a1[i], a2[i]))
            return false;
    }

    return true;
}

function indexOf(value:Array, into:Array):int{
    var i:int = -1;
    into.some(
        function(item:*, index:int, array:Array):Boolean {
            if (isArrayEquals(item as Array, value)) {
                i = index;
                return true;
            }
            return false;
        }
    );
    return i;
}

var i:int=indexOf([1,1], [[-1,1], [0,1], [1,1], [1,-1]]);
trace(i);

var j:int=indexOf([1,2], [[-1,1], [0,1], [1,1], [1,-1]]);
trace(j);

答案 2 :(得分:0)

这是有效的。可能是因为输入了内部数组。

var qwer:Array = [1,1];
var asdf:Array = [qwer];
trace( asdf.indexOf( qwer ) ); // 0