从 JavaScript 中的数组找出最接近的数字
我们需要编写一个 JavaScript 函数,该函数将数字数组作为第一个参数并且将单独的数字作为第二个参数。
该函数应找到并从该数组中返回一个数字,其最接近第二个参数指定的数字。
例如 -
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP