Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionScript Comparing Arrays

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 Sprite
{
private static const DEFAULT_ARRAY:Array = new Array(1, 2, 3);

public function myClass()
{
var test:Array = new Array(1, 2, 3);
trace (test == DEFAULT_ARRAY);
}

//traces false
like image 224
Chunky Chunk Avatar asked May 22 '10 23:05

Chunky Chunk


2 Answers

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.

like image 87
Juan Pablo Califano Avatar answered Sep 18 '22 22:09

Juan Pablo Califano


Dude, use the mx.utils.ObjectUtil... the creators of actionscript have already thought about this.

ObjectUtil.compare(this.instructions, other.instructions) == 0;
like image 42
Choppy The Lumberjack Avatar answered Sep 17 '22 22:09

Choppy The Lumberjack