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
廣告