gpt4 book ai didi

javascript - 对数组进行排序、将值插入该数组并返回最低索引的函数

转载 作者:行者123 更新时间:2023-11-28 11:53:25 24 4
gpt4 key购买 nike

我正在处理一个 JavaScript 挑战,要求您编写一个函数来:“返回应将值(第二个参数)插入到排序数组(第一个参数)中的最低索引。例如, where([1,2,3,4], 1.5) 应返回 1,因为它大于 1(第 0 个索引),但小于 2(第一个索引)。”

提示指示使用内置的“.sort()”方法,在这次挑战之前我不熟悉该方法。以下是我到目前为止所拥有的,我认为我还很遥远。

function where(arr, num) {
arr.push(num).sort(function(a,b){return a-b;});
return arr.indexOf(num);
}

console.log(where([40, 60], 50)); // returns "unexpected identifier"

最佳答案

拆分两个语句。

function where(arr, num) {
arr.push(num);
arr.sort(function(a, b) {
return a - b;
});
return arr.indexOf(num);
}

console.log(where([40, 60], 30)); // 0
console.log(where([40, 60], 50)); // 1
console.log(where([40, 60], 70)); // 2

关于javascript - 对数组进行排序、将值插入该数组并返回最低索引的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31213738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com