gpt4 book ai didi

javascript - 使用javascript查找最接近的数组索引

转载 作者:行者123 更新时间:2023-12-03 07:11:09 26 4
gpt4 key购买 nike

我有以下功能:

(function(){
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
var _array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362],
_number = 155;

return closest (_number, _array);
})()

结果是 162


在这个数组中,我想显示最接近结果的索引!结果应该是数字 4

最佳答案

您可以存储索引并返回该值。

function closest(num, arr) {
var curr = arr[0],
diff = Math.abs(num - curr),
index = 0;

for (var val = 0; val < arr.length; val++) {
let newdiff = Math.abs(num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
index = val;
}
}
return index;
}

var array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362],
number = 155;

console.log(closest(number, array));

关于javascript - 使用javascript查找最接近的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60028904/

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