【发布时间】:2021-10-14 14:16:31
【问题描述】:
我想找出数组中数字最小的元素的索引。 例如:函数 getIndexToIns([3, 2, 10, 7], 4) 将返回 2,因为如果将 4 插入到数组中,则数组应按升序排列为 [2, 3, 4, 7, 10]。而 4 的索引为 2。
我的代码 sn-p 如下,它显示错误“TypeError: newArr.sort is not a function”
function getIndexToIns(arr, num) {
newArr = arr.push(num);
newArr.sort((a, b) => a-b);
return newArr.indexOf(num)
}
getIndexToIns([2, 10, 4], 50);
console.log(getIndexToIns([2, 10, 4], 50))
我的代码 sn-p 有什么问题???
【问题讨论】:
-
arr.push(num) 返回一个数字,而不是一个数组
-
您尝试解决的任务似乎根本不需要排序。您可以只计算数组中有多少项小于
num。如果它是有序插入的,那将是num的索引。在[3, 2, 10, 7]中,有两个项目少于4。因此索引为2。 -
我想通了。非常感谢大家! :))
标签: javascript arrays sorting