为什么此for循环仅迭代一次?

时间:2019-11-22 14:37:40

标签: javascript for-loop

我不知道为什么这个for循环只迭代一次。 请注意,我是JavaScript的新手。

function bubbleSort(nums) {
    bubbleSortedArray = nums;
    lenOfBSA = bubbleSortedArray.length;
    for (i = 0; i < lenOfBSA; i++) {
        for (j = 0; j < lenOfBSA - i - 1; j++) {
            if (bubbleSortedArray[j] > bubbleSortedArray[j + 1]) {
                swap(bubbleSortedArray, j, j + 1);
                showSorting(bubbleSortedArray); // when i comment this out and call it elsewhere it works
            }
        }
    }
}

function showSorting(nums) {
    canvasprops = setup();
    cc = canvasprops[0];
    c = canvasprops[1];
    cc.clearRect(0, 0, c.width, c.height);
    cc.fillStyle = "lime";
    cc.fillRect(0, 0, c.width, c.height);

    console.log("updated canvas");

    var x = 0;
    cc.fillStyle = "black";
    for (i = 0; i < nums.length; i++) {
        cc.fillRect(x, c.height, 8, 6 * -nums[i]);
        x = x + 8;
    }
}


function setup() {
    var c = document.getElementById("sort-viewer");
    cc = c.getContext("2d");
    c.setAttribute("width", "800px");
    c.setAttribute("height", "620px");
    return [cc, c];
}

function swap(arr, a, b) {
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
    console.log("swapped");
}

当我从嵌套的for循环中注释掉showSorting(bubbleSortedArray);并将其放在for循环的末尾时,它会起作用,并且for循环会重复多次。但是,当它位于嵌套的for循环中时,由于某种原因只会发生一次迭代。

这里的要点是,我试图每次都绘制到画布上,以显示正在排序的数组(尝试创建可视化效果)。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

您不是在声明我。然后,它是一个全局变量,并被所有迭代器使用。您的showSorting函数正在更改i,因此for循环退出。

for(i = 0;i < 10; i++){
   // here i is global since it is not declared and scoped to the for loop
}

for(var i = 0;i < 10; i++){
   // here i is declared and initilized, and scoped to the current function
}
// which means I can access i here:
console.log(i); // outputs 9

for(let i = 0; i < 10; i++){
   // here i is declared and initilized and scoped to the loop only. i is not accessible outside of this loop.
}

将for循环更改为使用let i = 0而不是i = 0,它应该可以工作。