Array comparisons not making sense to me

Why does this return false?

private var stuff = new Array();

function Start () {
	stuff = ["1"];
}	

function Update ()  {
	print (stuff == ["1"]);
}

I’m not sure why yours returns false, but I modified it a little and this code will return true:

private var stuff = new Array(); 

function Start () { 
   stuff = ["1"]; 
}    

function Update ()  { 
   print (stuff[0] == "1"); 
}

Does this help any?

You are assigning “1” to the first index of the array. i.e. stuff[0] = 1
You then ask if the array object is equal to “1” , which it is not.

Hope that makes sense :slight_smile:

The comparison operator for Arrays will only check if both sides point to the same array and not whether the contents are identical.

This example will print true:

private var stuff = new Array();

function Start () {
	stuff = ["1"];
}	

function Update ()  {
	var copy_of_stuff = stuff;
	print (stuff == copy_of_stuff);
}

note that in the above example, copy_of_stuff refers to the same Array object and therefore the following will print 2 and not 1:

private var stuff = new Array();

function Start () {
	stuff = ["1"];
}	

function Update ()  {
	var copy_of_stuff = stuff;
	copy_of_stuff[0]="2";
	print (stuff[0]);
}

Yuck. That’s not going to cut it for me here. Is there any workaround to this? I’m inexperienced, and I don’t see the usefulness of comparing one Array to itself.

You just have to use the index to compare the values, like what Daniel said. Without the index you’re comparing the array objects, with the index you’re comparing the actual values at that location.

You have to compare every element individually. For instance like this:

// Put this in a file called ArrayUtil.js
static function CompareContents(a : Array, b : Array) {
    // If both arguments point to the same object, return true:
    if ( a == b ) 
        return true; 

    // If the arrays are of different length then they can't have 
    // equal contents:
    if ( a.length != b.length )
        return false; 

    // Else loop through each element and return false if any
    // of them differ:
    for ( var i=0; i < a.length; i++ ) {
        if( a[i] != b[i] )
            return false;
    }

    // If we reach this point, then both arrays contain the same:
    return true;
}

… and then use it like this:

private var stuff : Array; 

function Start () { 
   stuff = ["1"]; 
}    

function Update ()  { 
   print ( ArrayUtil.CompareContents(stuff, ["1"]) ); 
}

Great! I’ve learned more about coding today than I have in the past couple of months.