【问题标题】:Removing alert from code forces it to enter infinite loop从代码中删除警报会强制它进入无限循环
【发布时间】:2019-11-07 11:46:13
【问题描述】:

我有一段代码,其中包含一些窗口警报消息。它工作正常。但是,如果我删除警报语句,程序将进入无限循环。这对我来说很奇怪。

有人可以帮我找出代码的问题吗?

function countSwaps(arr) {

    let notVisited = {}, swaps = 0;
    for (let i = 0; i < arr.length; i++) {
        notVisited[i] = true;
    }

    while (Object.keys(notVisited).length) {
        alert("main pass");
        let nextPos, currentPos = Object.keys(notVisited)[0];
        while (arr[currentPos] !== parseInt(currentPos+1)) {
            nextPos = arr[currentPos] - 1;
            [arr[currentPos], arr[nextPos]] = [arr[nextPos], arr[currentPos]];

            swaps+= 1;
            alert("Swap " + arr[currentPos] + " and " + arr[nextPos] + "\n");
            delete notVisited[nextPos];
        }
        delete notVisited[currentPos];
    }
    return swaps;
}
console.log(countSwaps([2,3,4,1,5]));

【问题讨论】:

  • 即使存在警报,内部循环也在循环。
  • 注意:切勿使用alert 进行调试。它改变了代码的时间。使用调试器和/或console.log

标签: javascript arrays sorting object alert


【解决方案1】:

好吧,它也为我运行了一个无限循环,而没有警报。

问题似乎是以下表达式:parseInt(currentPos+1)

加法发生在从字符串转换为数字之前,例如:

currentPos = '4';
currentPos + 1 == '41';
parseInt(currentPos + 1) == 41

你想要的可能是parseInt(currentPos) + 1。现在:

currentPos = '4';
parseInt(currentPos) + 1 == 5

这样循环似乎退出了,我得到了 3 次交换的结果。

【讨论】:

    【解决方案2】:

    这是无限循环的原因。

    while (Object.keys(notVisited).length) 
    

    应该是这样的

    while (Object.keys(notVisited).length > 0)
    

    这是一个属性,它会一直返回true

    【讨论】:

      猜你喜欢
      • 2013-12-30
      • 2013-11-13
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2021-05-10
      相关资源
      最近更新 更多