最小数量不包括零 [英] Minimum number excluding zero
问题描述
我需要从数字列表中找到最小数字,不包括零。
I need to find minimum number from list of numbers, excluding zero(s).
是否有一些内部函数可以做到这一点?或者,在使用 Math.min
之前,是否必须从列表中删除零?
Is there some internal function that would do that? Or do I have to remove zero(s) from list before Math.min
is used?
示例:
输入: 213
, 0
, 32
, 92
, 0
, 2992
, 39
结果: 32
[更新] 如果可能,请提供代码用于将输入作为参数的函数,例如 nonZeroMin(213,0,32,92,0,2992,39)
[UPDATE] If possible, please provide code for function that would take inputs as arguments, such as nonZeroMin(213, 0, 32, 92, 0, 2992, 39)
推荐答案
代码/解决方案:
var arr = [3, 0, 7, 12, 0, 5, 22];
var minValue = Math.min.apply(null, arr.filter(Boolean));
工作原理:
arr.filter
创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。所以在上面的代码中,数组的每个值都将通过布尔值(值)进行测试
arr.filter
creates a new array with all elements that pass the test implemented by the provided function. So in the code above each value of the array will be tested by Boolean(value)
Boolean(3) // true
Boolean(0) // false
Boolean(7) // true
// ...
因此,我们将使用除零之外的所有元素的新过滤数组。
So as a result we will have new filtered array with all elements except zeros.
然后 Math.min.apply(null,...)
在这样的数组中找到最小值。
Then Math.min.apply(null, ...)
find min value in such array.
null
在这种情况下是一个上下文。它可以是 null
,这个
,数学
- 结果将是是一样的。
null
is in this case a context. It can be null
, this
, Math
- result will be the same.
这篇关于最小数量不包括零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!