var counts = [2, 33, 61, 92, 125, 153, 184, 215, 245, 278, 306, 335, 365],
goal = 35;
let min = Math.min(...counts.filter(num => num >= goal));
console.log(min)
这是有效的,但在goal=400
的情况下,我将返回365,因为它是数组中的最后一个数字
您可以找到所需的值,也可以在最后一个索引中获取值。
const
find = (array, value) => array.find((v, i, { length }) =>
v >= value || i + 1 === length
),
counts = [2, 33, 61, 92, 125, 153, 184, 215, 245, 278, 306, 335, 365];
console.log(find(counts, 35));
console.log(find(counts, 400));
如果undefined
。
const
find = (array, value) => array.find(v => v >= value) ?? array.at(-1),
counts = [2, 33, 61, 92, 125, 153, 184, 215, 245, 278, 306, 335, 365];
console.log(find(counts, 35));
console.log(find(counts, 400));
这将为您提供高于目标的最小数字,如果没有高于目标的数字,则为计数中的最大数字
const counts = [2,33,61,92,125,153,184,215,245,278,306,335,365]
goal = 35;
const above_goal = counts.filter(num => num >= goal)
const min = above_goal.length === 0 ? Math.max(counts) : Math.min(above__goal)
console.log(min)