从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 红包祝福语简短10字
18 周六早晨祝福语简短