获取数组中最接近(但更高)的数字 [英] Get closest (but higher) number in an array
本文介绍了获取数组中最接近(但更高)的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数字说 165
I have a number say 165
我有一个包含数字的数组.像这样:
I have an array with numbers in it. Like this:
[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
我希望我得到的数字更改为最接近但更高的数组数字.
I want that the number I've got changes to the nearest, but higher number of the array.
例如我得到 165 它应该达到 202
For example I get 165 it should go tot 202
javascript 数组
javascript arrays
推荐答案
这是一个使用 Array.forEach()
的方法:
Here's a method using Array.forEach()
:
const number = 165;
const candidates = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
//looking for the lowest valid candidate, so start at infinity and work down
let bestCandidate = Infinity;
//only consider numbers higher than the target
const higherCandidates = candidates.filter(candidate => candidate > number);
//loop through those numbers and check whether any of them are better than
//our best candidate so far
higherCandidates.forEach(candidate => {
if (candidate < bestCandidate) bestCandidate = candidate;
});
console.log(bestCandidate); //the answer, or Infinity if no valid answers exist
这篇关于获取数组中最接近(但更高)的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文