从JavaScript数组中获取最接近的数字
我们需要编写一个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
热门推荐
10 母亲说生日祝福语 简短
11 毕业祝福语简短英语小学
12 高考已上岸祝福语简短
13 生日祝福语简短激励女生
14 今年节日祝福语简短
15 简短有力的结婚祝福语
16 新大学开学祝福语简短
17 档案调动孩子祝福语简短
18 发给导师的祝福语简短