[英]JS: find lowest/highest number from array within a specific range
I have an array with a few nums: 我有一些数字数组:
var arr = ["10","14","23","2","21","17","72","16","73","52"];
I know I can use Math.min.apply(Math, arr)
to get from an array the lowest number or use Math.max.apply(Math,arr)
for the maximum number, but now I want only the minimum or maximum number from the last 3 elements in the array. 我知道我可以使用
Math.min.apply(Math, arr)
从数组中获取最小数,也可以使用Math.max.apply(Math,arr)
作为最大数,但是现在我只想要最小或最大数从数组的最后3个元素开始。
Any suggestions how I could do this? 有什么建议我该怎么做?
Using Array.prototype.slice()
, you can extract a range of values within an array. 使用
Array.prototype.slice()
,可以提取数组中的一系列值。 This will allow you to only perform the min()
and max()
function on the values within the designated range. 这将允许您仅对指定范围内的值执行
min()
和max()
函数。
The minmax()
function below will return an object with min
and max
values. 下面的
minmax()
函数将返回具有min
和max
的对象。
function minmax(arr, begin, end) { arr = [].slice.apply(arr, [].slice.call(arguments, 1)); return { 'min' : Math.min.apply(Math, arr), 'max' : Math.max.apply(Math, arr) } } var values = ["10","14","23","2","21","17","72","16","73","52"]; var result = minmax(values, -3); document.body.innerHTML = JSON.stringify(result, undefined, ' ');
body { font-family: monospace; white-space: pre; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.