JavaScript 中最接近元素的索引

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/9 4:28:17

假设我们有一个像这样的数组 −

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

相关文章


有用资源