Why these two arrays are not equal, please?

Martin.Jirsak's icon

Hi,

I have this JS code:
********************************************************
var tempValue = [];

function getValue (value) {
    var currentValue = [];
    currentValue[0] = [value, 1, 1];

    if (tempValue[0] == null) {
    } else {
        if (currentValue[0] == tempValue[0]) {
            post ("==");
        } else {
            post ("!=");
        }
    }

    tempValue[0] = currentValue[0];
}
********************************************************
To the getValue function, I pass the same number multiple times (first to fill in the tempValue[0]; second to test). As the result always "!=" is posted. Why?

Thanks in advice.

mzed's icon

This looks like the JS should log nothing the first time, and either != or == on subsequent times. I think your code is ok.

Martin.Jirsak's icon

Thank you for the answer.

What is weird, if I test "if (currentValue[0] == tempValue[0])" immediately after the assignment "tempValue[0] = currentValue[0];", so the snipped looks like this:

tempValue[0] = currentValue[0];
if (currentValue[0] == tempValue[0]) {...}

then the result is true. But if I test it before (during the 2nd run), then the result is false.

If I test every single value of the arrays agains each other

((currentValue[0][0] == tempValue[0][0]) &&
(currentValue[0][1] == tempValue[0][1]) ...

then the result of all tests is also true.

I'm sorry, I was wrong. For the very first run, JS logs null. But then for every single run, it always logs "!=". I would expect "==".

Nikolas K's icon

Hi Martin,

I'm not 100% sure, but I think that because you store an array in the array, it is essentially an object.
So the elements stored in both currentValue[0] and tempValue[0] are JS objects, and are not the same one, so since they are not the same object, comparing them should always be false.

-N

Jesse's icon

Nikolas is correct - you're comparing Array objects, which are in separate memory spaces even if their contents are the same.

Martin.Jirsak's icon

So the solution is to test all in-array elements against the same element in the 2nd array, rigt?

Would it help, if I make the currentValue also a global variable?

Nikolas K's icon

Yes, you have to check it element for element. It would be easier on the long run, if you haven't already, to make a .js file in the Max's "jsextensions" folder and just store your array-comparing function there (along with other of your "utilities" functions).
Just be careful if you are on a Mac, when you update/reinstall Max, the file will be deleted, so back it up!

Making it a global object won't do any difference as the comparison is still done with two objects (the two arrays).

-N