Home  >  Article  >  Web Front-end  >  JavaScript finds the maximum and minimum value in an array

JavaScript finds the maximum and minimum value in an array

黄舟
黄舟Original
2017-02-23 13:51:391527browse

The minimum value algorithm is as follows:

  1. Assign the first element in the array to a variable and use this variable as the minimum value;

  2. Start traversing the array, starting from the second element and comparing it with the first element in sequence;

  3. If the current element is less than the current minimum value, replace the current Assign the element value to the minimum value;

  4. Move to the next element and continue the third step;

  5. 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:

  1. Assign the first element in the array to a variable, Use this variable as the maximum value;

  2. Start traversing the array, starting from the second element and comparing it with the first element in sequence;

  3. If the current element is greater than the current maximum value, assign the current element value to the maximum value;

  4. Move to the next element and continue the third step;

  5. 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)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn