为什么只有一个应该改变这两个变量?

时间:2019-07-01 01:47:53

标签: javascript loops scope dynamic-arrays

以下是我从主程序中删除的子例程。它可以作为独立脚本执行,但其行为方式不会像在主程序中那样好:

//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);
}

只有两个“ 2D”数组中的一个可以更改,但是如您从终端窗口输出的以下屏幕截图中看到的,两者都做:output of simple subroutine。我对范围/关闭/等方面的了解仍然很不稳定,但是我的怀疑在于那个方向。任何帮助将不胜感激(包括简要说明),但是我特别热衷于最简单的纠正方法来完成这项工作。

先谢谢了,
罗布

1 个答案:

答案 0 :(得分:0)

var direction_pairs_being_tried = potential_direction_pairs;不是数组的副本,它指向同一数组。您可以使用

复制数组
var direction_pairs_being_tried = potential_direction_pairs.slice()