首页 > 解决方案 > Can someone explain how this finds the max number?

问题描述

var myArray = [1, 12, 3, 5, 6];
var maxValue = null;
for (var i = 0; i < myArray.length; i++) {
    if (maxValue === null || maxValue < myArray[i]) {
        maxValue = myArray[i];
    }
}
// shows 12

I see that it loops through myArray and checks if maxValue is equal to null (which it is?) OR if maxValue is less than current array element (which it also is?) and then assigns maxValue to the current array element in for loop. How does this find the largest number? Seems so simple but I don't see how it's finding largest integer ...

标签: javascript

解决方案


将初始值替换为 0 并删除空测试使其更易于阅读。添加一个 console.log 可以让你跟踪循环的执行。

var myArray = [1, 12, 3, 5, 6];
var maxValue = 0;
for (var i = 0; i < myArray.length; i++) {
    console.log( i, myArray[i], maxValue );
    if (maxValue < myArray[i]) {
        maxValue = myArray[i];
    }
}
// shows 12


推荐阅读