1

我有从数组中获得最近似值的代码。但我只想获得最高价值。我想说的是,如果我输入 value760这应该给我带来 value800而不是 value 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;
  }
}

始终从上方获取价值,从不向下。希望我解释清楚。问候

4

5 回答 5

3

您正在寻找的是与谓词匹配的第一个项目。这里的谓词是保持第一项大于 x。

我们使用Array.prototyp.find

find()方法返回数组中满足提供的测试函数的第一个元素的值。否则返回。undefined

// 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))

于 2019-02-07T15:36:38.777 回答
3

您正在按距离排序并获得距离最小的项目。为了获得稍小的值,您需要在升序排序的数组中找到该值。

function validate_ancho(x) {
  var array = [600, 650, 700, 750, 800, 900, 950, 1000],
      closest = array.find(v => v >= x) || array[array.length - 1],
      ancho_validate = closest - x;

  console.log(closest);
  return ancho_validate > 20;
}

console.log(validate_ancho(760));

于 2019-02-07T15:36:19.347 回答
0

您还可以过滤数组

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.filter(function(z){ return z > x;}).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;
  }
}

于 2019-02-07T15:41:03.480 回答
0

这是因为你的算法是错误的。您发布的代码正在选择具有最低绝对值的值。因此,它是最接近的。

您要求的是不小于输入变量的最接近的值。

所以过滤掉高于 x 的值。

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.filter(a => a > x).sort((a, b) => a - b)[0];
  var ancho_validate = closest - this_ancho;

  console.log(ancho_validate);

  if (ancho_validate > 20) {
    return true;
  } else {
    return false;
  }
}

或者,您也可以Array.reduce一次性使用:

closest = array.reduce((acc, cur) => cur > x && (acc == null || cur < acc) ? cur : acc, null)
于 2019-02-07T15:50:43.497 回答
-1

let array = [600, 650, 700, 750, 800, 900, 950,1000];
let myNumber = 960;
let closest = array.filter((el) => el > myNumber)[0];
console.log(closest)

于 2019-02-07T15:38:37.463 回答