Javascript Array value [closed]

I think your explanation it is hard to understand. Your are comparing an object with a number after you incremented the type, so conditions won’t met

function checkClick (mouseEvent) {
    for (i = 0; i < all_rails.length; i++) {
        if (mouse_x < all_rails[i].x + 32 && mouse_x > all_rails[i].x && mouse_y >         all_rails[i].y && mouse_y < all_rails[i].y + 32) {
            if (all_rails[i] !== 0) {
                /*
                    Always happens, all_rails[i] is an object, not the number 0
                */
                all_rails[i].type++;  // Always increment
                if (all_rails[i] == 1 && all_rails[i].type > 1) {
                    /*
                        Never happens, all_rails[i] is an object, not a value 1
                    */
                    all_rails[i].type = 0; // Never resets
                }
                else if (all_rails[i] == 2 && all_rails[i].type > 3) {
                    /*
                        Never happens, all_rails[i] is an object, not a value 2
                    */
                    all_rails[i].type = 0; // Never resets
                }
            }
        }
    }
}

You declared all_rails as:

var all_rails = [0, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1,];

but in make_rail you assign an object s_rail or object c_rail to all the items, overriding the initial numerical value.
Available fixes are add a custom valueOf to the c_rail and s_rail objects that evaluates to the initial all_rails[n] value (not recommended) or add a new property that holds the initial numerical value and pass it as an argument to the c_rail and s_rail constructors, then fix checkClick function to compare the property of all_rails[i] rather than the object itself.

(I will also recommend that in JavaScript you declare everything first before you execute actual code. Also to use capitalize the first letter of the constructor and use camel case)

Leave a Comment