ActionScript Comparing Arrays

后端 未结 3 1630
既然无缘
既然无缘 2021-01-05 15:26

how can i evaluate whether my test array is equal to my static constant DEFAULT_ARRAY? shouldn\'t my output be returning true?

public class myClass extends          


        
3条回答
  •  离开以前
    2021-01-05 15:58

    Macke has already pointed out the problem. The == operator will tell you (for reference types such as Array objects) if two variables point to the same object. That's clearly not the case here. You have 2 different objects, that happen to have the same content.

    So, what you're probably looking for is a way to compare whether 2 arrays have the same contents. This apparently simple task might be trickier than it seems.

    The standard way is using a function like this:

    function areEqual(a:Array,b:Array):Boolean {
        if(a.length != b.length) {
            return false;
        }
        var len:int = a.length;
        for(var i:int = 0; i < len; i++) {
            if(a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    }
    

    This will work in some (arguably most) cases. But it will fail if the items in any of the arrays have reference type semantics (as opposed to value type semantics). Basically, Numbers (including ints and uints), Strings, Boolean, null and undefined have value type semantics:

    Given:

    var a:int = 0;
    var b:int = 0;
    

    This will hold true:

    trace(a == b);
    

    For everything else, comparing with == will only return true if both vars reference the same object:

    var a:Object = {data:1};
    var b:Object = {data:1};
    
    trace(a == b); // false
    

    But

    var a:Object = {data:1};
    var b:Object = a;
    
    trace(a == b); // true
    

    So, if your arrays contain objects (or in turn other Arrays), the areEqual will fail in this case:

    var arr_1:Array = [{data:1}];
    var arr_2:Array = [{data:1}];
    
    trace(areEqual(arr_1,arr_2));
    

    Why? Because the {data:1} object that you stored in arr_1 is different from the {data:1} object stored in arr_2.

    I don't think it's possible to create a generic function that checks recursively whether two arrays' contents are equal, because there's no generic way of determinig whether two objects should be considered equal. This really depends on your objects, your domain, etc. I.e. in your app, two objects should be considered equal if they have the same ìd (assuming you have defined an ìd property). As I think this shows, there's no way to know before hand what makes to objects equal.

提交回复
热议问题