找到最小值,零除外

时间:2015-03-26 21:00:09

标签: javascript

我正在使用Math.min()查找最低价格,但如果产品不可用,有时传递的变量可能会0

Math.min( 101.06, 99.99, 0 );

..在这种情况下,结果为0。如何过滤掉它?

3 个答案:

答案 0 :(得分:3)

我猜你想要最小的正数:

function positiveMin(arr) {
  var min;
  arr.forEach(function(x) {
    if (x <= 0) return;
    if (!min || (x < min)) min = x;
  });
  return min;
}

positiveMin([101.06, 99.99, 0, -1]); // => 99.99
positiveMin([0]); // => undefined

答案 1 :(得分:3)

您可以使用.apply将参数作为数组传递,

  

fun.apply(thisArg,[argsArray])

- https://developer.mozilla.org/

这意味着您可以过滤参数,检查您想要的任何属性。

所以,在你的情况下,只需:

Math.min.apply(this, [101.06, 99.99, 0].filter(Number) );

这种方法也有其他好处,看起来你会动态生成你的参数,传递生成的数组比实际的参数更容易。

答案 2 :(得分:0)

这是一个简单的功能:

Math.positiveMin = function(){
  arguments = Array.prototype.slice.call(arguments);
  return arguments.reduce(function(min, current){
    return (current > 0 && current < min) ? current : min;
  }, arguments[0]);
};
如果没有大于0的参数,则

返回零。

这种方法可能比我之前的好处:你在你的例子中单独传递参数,你可以用这种方法做到这一点:

Math.positiveMin( 101.06, 99.99, 0 );

将按预期工作,无需数组。

相关问题