The minimum value algorithm is as follows:
Assign the first element in the array to a variable and use this variable as the minimum value;
Start traversing the array, starting from the second element and comparing it with the first element in sequence;
If the current element is less than the current minimum value, replace the current Assign the element value to the minimum value;
Move to the next element and continue the third step;
When the array element traversal ends , this variable stores the minimum value;
The code is as follows:
// 查找数组中最小值 function arrayMin(arrs){ var min = arrs[0]; for(var i = 1, ilen = arrs.length; i < ilen; i+=1) { if(arrs[i] < min) { min = arrs[i]; } } return min; } // 代码测试 var rets = [2,4,5,6,7,9,10,15]; console.log(arrayMin(rets));//2
The above compares the values in the array, if the number in the array is a string If so, you need to convert the string into a number first and then compare it, because the string comparison is not the value, but the ASCII code. For example, the ASCLL code of 2 will be greater than the ASCII code of 15, because the first number of the code of 15 is The ASCII encoding of 1 and 2 is definitely greater than 1;
The algorithm for finding the maximum value is similar to the above:
Assign the first element in the array to a variable, Use this variable as the maximum value;
Start traversing the array, starting from the second element and comparing it with the first element in sequence;
If the current element is greater than the current maximum value, assign the current element value to the maximum value;
Move to the next element and continue the third step;
When the array element traversal ends, this variable stores the minimum value;
The code is as follows:
// 在数组中查找最大值 function arrayMax(arrs) { var max = arrs[0]; for(var i = 1,ilen = arrs.length; i < ilen; i++) { if(arrs[i] > max) { max = arrs[i]; } } return max; } // 代码测试 var rets = [2,4,5,6,7,9,10,15]; console.log(arrayMax(rets));//15
The above is the JavaScript search The content of the maximum value and minimum value in the array. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!