Search code examples
javascriptloopsscopedynamic-arrays

Why do both of these variables change when only one is supposed to?


The following is a subroutine that I excised from my main program. It executes as a stand-alone script, but does not behave in the intended manner any better than it did in the main program:

//Generate permanent array of all possible directional marker pairs,
//excluding 0,0. Also generate array length the "hard" way

var potential_direction_pairs = [];
var length_of_potential_direction_pairs_array = 0;
for (var x_count = -1; x_count < 2; x_count++) {
    for (var y_count= -1; y_count < 2; y_count++) {
        if (x_count == 0 && y_count == 0) {}
        else {
            potential_direction_pairs.splice(0, 0, [x_count, y_count]);
            length_of_potential_direction_pairs_array += 1
        }   
    }
}

//Create temporary and mutable copy of permanent directional marker array.
var direction_pairs_being_tried = potential_direction_pairs;

//Iterate over all elements in temporary marker array. Use permanent array
//length, as temporary array length will change with each loop.
for (var count = 0, current_direction_pair_being_tried; count < length_of_potential_direction_pairs_array; count++) {

    //Count out current length of (shrinking) temporary array.
    for (var pair_index = 0; direction_pairs_being_tried[pair_index] != undefined; pair_index++) {}

    //Choose a random marker pair from temporary array...
    var random_index = Math.floor(Math.random() * pair_index);

    //...and store it temporarily in a single-pair array.
    current_direction_pair_being_tried = direction_pairs_being_tried[random_index];

    //Remove the randomly chosen marker pair from larger temporary array.
    direction_pairs_being_tried.splice(random_index, 1);

    //Insert temporary "tracer" to display current state of intended
    //"permanent" array.
    console.log("Potential direction pairs: " + potential_direction_pairs);

    //Insert another "tracer" to display current state of intended
    //temporary array.
    console.log("Direction pairs being tried: " + direction_pairs_being_tried);

    //"Tracer" showing current state of temporary single-pair array.
    console.log("Current direction pair being tried: " + current_direction_pair_being_tried);
}

Only one of the two "2D" arrays is meant to change, but as you can see from the following screenshot of terminal window output, both do: output of simple subroutine. My knowledge of scope/closure/etc is still pretty shaky, but my suspicions lie that direction. Any help would be appreciated (including a brief explanation), but I'm especially keen on the simplest possible correction to make this work.

Thanks in advance,
Rob


Solution

  • var direction_pairs_being_tried = potential_direction_pairs; is not a copy of an array, it's pointing to the same array. You can copy an array with

    var direction_pairs_being_tried = potential_direction_pairs.slice()