Math.max.apply/Math.min.apply get the maximum and minimum values of the array

Use Math.max/Math.min to find the maximum/minimum value in the array

/* 找出数组中最大/小的数字 */
var numbers = [5, 6, 2, 3, 7];

/* 使用Math.min/Math.max以及apply 函数时的代码 */
var max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);

/* 对比:简单循环算法 */
max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
    
    
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min)
    min = numbers[i];
}

Note: If you call apply as above, there is a risk of exceeding the upper limit of the JavaScript engine parameter length. The consequences of passing too many parameters (such as 10,000) to a method are different in different JavaScript
engines. (There is an
upper limit for the number of hard-coded parameters in the JavaScriptCore engine : 65536). This is because this restriction (actually a natural manifestation of any behavior that uses a large stack space) is ambiguous. Some engines will throw exceptions, and worse, other engines will directly limit the number of parameters passed into the method, causing parameters to be lost. For example, suppose the upper limit of the method parameter of a certain engine is 4 (in fact, the limit is much higher). In
this case, after the above code is executed, the parameters that are actually passed to apply are 5, 6, 2, 3, and Not a complete array.

If your parameter array may be very large, then it is recommended to use the following hybrid strategy: Divide the array and pass it to the target method circularly:

/** 切片循环获取数组最大最小值
* @Descripttion: 解决apply中因参数过长导致参数丢失问题
* @param {*} arr
* @param {*} type 'min' or 'max'
* @return {*}
* @Author: TinaZ
* @Date: 2021-02-24
*/
function fnGetMinOrMaxOfArray(arr,type) {
    
    
	var val = 0;
	var QUANTUM = 3; // 切片限制 默认为32768(65536/2) 3为演示使用
	
	if(type == 'min'){
    
    
	   val = Infinity;
	   for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
    
    
	       var subval = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));
	       val = Math.min(subval, val);
	   }
	}
	if(type == 'max'){
    
    
	   val = -Infinity;
	   for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
    
    
	       var subval = Math.max.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));
	       val = Math.max(subval, val);
	   }
	}
	return val;
}
var min = fnGetMinOrMaxOfArray([0,1,2,3,4,5,6], 'min');
var max = fnGetMinOrMaxOfArray([0,1,2,3,9,5,6], 'max');
console.log('min',min) //0
console.log('max',max) //9

Reference: Use apply and built-in functions

Guess you like

Origin blog.csdn.net/weixin_42549581/article/details/114014487