JavaScript中最接近的元素的索引
假设我们有一个像这样的数组-
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组和一个数字,例如n。
该函数应从数组中返回最接近数字n的项目索引。
因此,让我们为该函数编写代码-
示例
为此的代码将是-
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
const closestIndex = (num, arr) => {
let curr = arr[0], diff = Math.abs(num - curr);
let index = 0;
for (let 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;
};
console.log(closestIndex(150, arr));输出结果
控制台中的输出将为-
4
热门推荐
4 孙媳妇祝福语简短
10 发给导师的祝福语简短
11 宝宝新年祝福语大全简短
12 员工对同事祝福语简短
13 横幅元旦祝福语大全简短
14 父亲简短结婚祝福语大全
15 致姐姐生日祝福语简短
16 开业祝福语简短大气的
17 新娘对伴娘祝福语简短
18 二胎祝福语简短霸气