我们需要编写一个JavaScript函数,该函数将Numbers数组作为第一个参数,将一个数字作为第二个参数。
该函数应从数组中查找并返回与第二个参数指定的数字最接近的数字。
例如-
const arr = [34, 67, 31, 53, 89, 12, 4]; const num = 41;
然后输出应为34。
以下是代码-
const arr = [34, 67, 31, 53, 89, 12, 4]; const num = 41; const findClosest = (arr = [], num) => { let curr = arr[0]; let diff = Math.abs (num - curr); for (let val = 0; val < arr.length; val++) { let newdiff = Math.abs (num - arr[val]); if (newdiff < diff) { diff = newdiff; curr = arr[val]; }; }; return curr; }; console.log(findClosest(arr, num));
输出结果
以下是控制台上的输出-
34