javascript - 总是接近最大值

标签 javascript jquery html

我有从数组中获取最近似值的代码。但我只想获得最高值(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. Otherwise undefined 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/

相关文章:

javascript - 旋转元素而不是从页面上滑动

javascript - 我们应该在表单状态中存储原始值还是解析值

javascript - 在javascript中按值作为键创建新对象

javascript - 在 mouseleave 上将图像恢复到悬停数据源所在位置之外的原始源

javascript - 使用了 .prop,现在按钮不可点击

jquery - 阅读跨度文本

jQuery 更改所有 <element> HTML 如果 HTML = Something

javascript - jQuery PJAX 插件不能在 HTML 网站上运行?

javascript - 选择特定 radio 时更改 "p"和 "img"的内容

javascript - 从 JavaScript 获取 SVG 文件作为字符串