我有从数组中获取最近似值的代码。但我只想获得最高值(value)。我想说的是,如果我输入值 760
,这应该给我带来值 800
,而不是值 750
。
validate_ancho(760);
function validate_ancho(this_ancho) {
var x = this_ancho;
var array = [600, 650, 700, 750, 800, 900, 950, 1000];
var closest = array.sort((a, b) => Math.abs(x - a) - Math.abs(x - b))[0];
var ancho_validate = closest - this_ancho;
console.log(ancho_validate);
if (ancho_validate > 20) {
return true;
} else {
return false;
}
}
总是从上面获取值(value),从不从下面获取。希望我解释清楚。问候
最佳答案
您要查找的是与谓词匹配的第一项。这里的谓词是保持第一项大于 x。
我们使用 Array.prototyp.find .
The
find()
method returns the value of the first element in the array that satisfies the provided testing function. Otherwiseundefined
is returned.
// we take a number as input and we output the closet higher number in the array
function validate_ancho(this_ancho) {
const array = [600, 650, 700, 750, 800, 900, 950, 1000];
const closest = array.find(x => x >= this_ancho);
return closest;
}
console.log(validate_ancho(760))
关于javascript - 总是接近最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54576788/