为什么这会产生无限循环?

时间:2021-04-27 19:14:25

This was one of my algorithm questions at FreeCodeCamp.com :

这是我在FreeCodeCamp.com上的算法问题之一:


Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.

If I don't put a break in my "if statement", I get a "potential infinite loop" warning. Why is that? I thought if the condition was false, the for loop would continue on to the next iteration.

如果我在“if语句”中没有中断,我会收到“潜在的无限循环”警告。这是为什么?我想如果条件是假的,for循环将继续到下一次迭代。

//my solution

function getIndexToIns(arr, num) {
  arr.sort(function(a, b) {
    return a - b;
  });

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > num) {
    //This is the code in question
       arr.splice(i, 0, num);
       break;
    }
    else {
      arr.push(num);
    }
  }
  return arr.indexOf(num);
}

1 个解决方案

#1


0  

The condition is never going to be false once you've inserted the number into the array, because arr[i] is always going to be the same element that got you into the if block in the first place - it's just been moved up one index.

一旦你将数字插入到数组中,条件永远不会是假的,因为arr [i]总是与第一个进入if块的元素相同 - 它刚刚被移动了一个指数。

var arr = [500];
var num = 100;

for (var i = 0; i < arr.length; i++) {
    if (arr[i] > num) {                // arr[0] = 500, so we enter the block

       arr.splice(i, 0, num);          // now the array is [100, 500], and the 
    }                                  // for loop is going to move onto arr[1]
                                       // which is still 500... so we'll enter the
                                       // if block again and insert another 100, etc etc.

#1


0  

The condition is never going to be false once you've inserted the number into the array, because arr[i] is always going to be the same element that got you into the if block in the first place - it's just been moved up one index.

一旦你将数字插入到数组中,条件永远不会是假的,因为arr [i]总是与第一个进入if块的元素相同 - 它刚刚被移动了一个指数。

var arr = [500];
var num = 100;

for (var i = 0; i < arr.length; i++) {
    if (arr[i] > num) {                // arr[0] = 500, so we enter the block

       arr.splice(i, 0, num);          // now the array is [100, 500], and the 
    }                                  // for loop is going to move onto arr[1]
                                       // which is still 500... so we'll enter the
                                       // if block again and insert another 100, etc etc.