简体   繁体   English

for循环没有找到数组的最大值(Javascript)

[英]For loop not finding max value of array (Javascript)

My function 'extremeValue' takes 2 parameters, an array and a string "Maximum" or "Minimum", and depending on that string it returns the maximum or minimum value of the array. 我的函数'extremeValue'有2个参数,一个数组和一个字符串“Maximum”或“Minimum”,根据该字符串,它返回数组的最大值或最小值。 I used an example array 'values' to pass through the function and while it works out the minimum just fine, the maximum comes out to be the last value of the array. 我使用了一个示例数组'values'来传递函数,当它计算出最小值时,最大值就是数组的最后一个值。 What's wrong with my code? 我的代码出了什么问题?

 var values = [4, 3, 6, 12, 1, 3, 7]; function extremeValue(array, maxmin) { if (maxmin === "Maximum") { var max = array[0]; for (var i = 1; i < array.length; i++) { if (array[i] > array[i-1]) { max = array[i]; } } return max; } else if (maxmin === "Minimum") { var min = array[0]; for (var j = 1; j < array.length; j++) { if (array[j] < array[j-1]) { min = array[j]; } } return min; } } console.log(extremeValue(values, "Maximum")); console.log(extremeValue(values, "Minimum")); 

Change the checking with maximum value. 使用最大值更改检查。

if (maxmin === "Maximum") {
    var max = array[0];
    for (var i = 1; i < array.length; i++) {
        if (array[i] > max) { //not just before 'array[i-1]'
            max = array[i];
        }
    }
    return max;
}

OR 要么

Simply Use 简单地使用

Math.max.apply( Math, values );

to find Maximum from values.and 从values.and找到Maximum

Math.min.apply( Math, values );

for minimum values. 最小值。

In each loop you must compare an item with maximum (or minimum) value, not before item: 在每个循环中,您必须将项目与最大(或最小)值进行比较,而不是在项目之前:

var values = [4, 3, 6, 12, 1, 3, 7];

function extremeValue(array, maxmin) {
    if (maxmin === "Maximum") {
        var max = array[0];
        for (var i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        return max;
    }
    else if (maxmin === "Minimum") {
        var min = array[0];
        for (var j = 1; j < array.length; j++) {
            if (array[j] < min) {
                min = array[j];
            }
        }
        return min;
    }
}

console.log(extremeValue(values, "Maximum")); 
console.log(extremeValue(values, "Minimum"));

Alternatively you can use the Math function to shorten your code: 或者,您可以使用Math函数缩短代码:

 var values = [4, 3, 6, 12, 1, 3, 7]; function extremeValue(array, maxmin) { if (maxmin === "Maximum") { return Math.max.apply(null, array); } else if (maxmin === "Minimum") { return Math.min.apply(null, array); } } console.log(extremeValue(values, "Maximum")); console.log(extremeValue(values, "Minimum")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM