首页 > 解决方案 > 如果大于数组中的其余整数,则将整数添加到数组末尾

问题描述

我的函数通过一个数组来找到它应该插入的最低索引。我假设数组总是排序的。除非整数大于数组的其余整数,否则它会起作用。此时,需要将其添加到数组的末尾。

我尝试使用 if else 语句并在数字后面加上 apush但它只是进入一个永无止境的循环,因为我将始终保持小于arr.length. 我尝试break在 else 内的 push 之后添加 a ,但是如果数组内已经有一个位置,它总是会追加而不插入到正确的位置。

function lowestIndexInsert(num,arr){
  for (i = 0; i<arr.length; i++){
      if (arr[i]>num){
      arr[i]=num;
      }
      else { 
        arr.push(num);
        break;
      }

  }
 return arr.indexOf(num);
}


lowestIndexInsert(15,[8,25,33,52,70]);// should return 1
lowestIndexInsert(80,[8,25,33,52,70]);// should return 5

标签: javascript

解决方案


您可以使用splice将元素插入到数组中,然后立即中断。完成此操作后,您可以捕获 i = length 并且尚未插入的最后一种情况。如果您使用 3 个参数,例如:.splice(start, deleteCount, insertMe)该函数将在特定索引处插入项目并且不删除。有了这个,你可以这样做:

function lowestIndexInsert(num,arr){
  for (i = 0; i<arr.length; i++){
      if (arr[i]>num){
          arr.splice(i, 0, num);
          // Break here to stop the loop after inserting
          break;
      }

      // Perform a final check to see if the item was inserted.
      if(i == (arr.length - 1)){
          arr.push(num);
      }

  }
 return arr.indexOf(num);
}


lowestIndexInsert(15,[8,25,33,52,70]);// should return 2
lowestIndexInsert(80,[8,25,33,52,70]);// should return 5


推荐阅读