二分法查找最接近的值
-
let arr = [1,5,9,13,17,20]; function findNearesttargetber(arr, target) { let mid; let min = 0; let max = arr.length - 1; while (max - min > 1) { mid = Math.floor((min + max) / 2); if (target < arr[mid]) { max = mid; } else { min = mid; }; }; // return Math.abs(target - arr[min]) <= Math.abs(target - arr[max]) ? arr[min] : arr[max]; return Math.abs(target - arr[min]) <= Math.abs(target - arr[max]) ? min : max; } console.log(findNearesttargetber(arr, 7));
-