例如,getIndexToIns([1,2,3,4], 1.5)
应该返回 1
因为它大于 1
(索引 0
),但小于 2
(索引 1
)。
同样,getIndexToIns([20,3,5], 19)
应该返回 2
因为一旦数组排序后它看起来像 [3 ,5,20]
和 19
小于 20
(索引 2
)且大于 5
(索引 1
)。
这是我的代码
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr = arr.sort();
num = Math.floor(num);
for(let i=0;i<arr.length;i++){
}
return num;
}
getIndexToIns([690, 60], 59);
最佳答案
您可以使用 .findIndex()
在排序数组中找到第一个大于传递的 num
元素的元素:
const getIndexToIns = (arr, num) => {
const res = arr.sort((a, b) => a-b).findIndex(n => n > num);
return res === -1 ? arr.length : res;
}
console.log(getIndexToIns([1,2,3,4], 1.5));
console.log(getIndexToIns([20,3,5], 19));
console.log(getIndexToIns([20,3,5], 100)); // 3 (array length)
关于javascript - 如何返回数组的最低索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59558349/