javascript - 如果大于数组中的其余整数,则将整数添加到数组末尾
问题描述
我的函数通过一个数组来找到它应该插入的最低索引。我假设数组总是排序的。除非整数大于数组的其余整数,否则它会起作用。此时,需要将其添加到数组的末尾。
我尝试使用 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
解决方案
您可以使用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
推荐阅读
- javascript - 如何在提交搜索时重定向到另一个组件?
- c - 如何仅从 clang AST 获取函数声明?
- python - OctavianAI最短路径图学习模型中的Tensorflow问题
- ajax - 在选择 Laravel 5.8 中使用 AJAX 时出现错误 500
- python - 如何删除列表形式的数据帧的重复索引?
- python - 识别python函数中全局变量的无意读/写?例如使用静态分析?
- acumatica - 如何在 Acumatica 移动框架中使用移动设备的相机
- python - 为什么Django rest框架中的时间不正确
- azure-devops - Azure devops 未在管道的报告(xml)部分的测试套件下显示测试套件名称
- xamarin - 无法从 Xamarin VS 2019 将 IPA 文件分发到 App Store