简体   繁体   English

JavaScript findMax()示例-需要说明

[英]JavaScript findMax() example - Need an Explanation

I'm going through a W3Schools tutorial on JavaScript and I was just wondering about this findMax() function: 我正在阅读有关JavaScript的W3Schools教程,而我只是想知道这个findMax()函数:

function findMax() {
    var i;
    var max = -Infinity;
    for (i = 0, i < arguments.length; i++) {
        if (arguments[i] > max) {
            max = arguments[i];
        }
    }
    return max;
}

I understand that 'i' is a counter, the function goes until everything has been counted, and the count is increased by 1. What I don't understand - how does creating an if statement (arguments[i] > max) ... get the highest number in the findMax() function? 我知道'i'是一个计数器,该函数一直执行到所有内容都计数完毕,并且该计数增加1。我不了解-如何创建if语句(arguments [i]> max)。 。在findMax()函数中获得最大的数字? Why does passing i into the if statement give the max number back? 为什么将i传递给if语句会返回最大数?

In that particular line of code, the loop is checking each value with the arguments array to see if it higher than the currently highest value saved in max . 在特定的代码行中,循环将使用arguments数组检查每个值,以查看其是否高于max保存的当前max If it is not, then it moves on to the next one. 如果不是,则移至下一个。 If it is, then it changes max to the new highest value. 如果是,则将max更改为新的最大值。 Once the loop has checked each value in the arguments array, then the function returns the highest value ( max ). 循环检查完arguments数组中的每个值后,该函数将返回最大值( max )。

The if statement doesn't look directly at the value of i. if语句不会直接看i的值。 Instead, it is used as an index to a specific value in the array arguments . 而是将其用作数组arguments特定值的索引。
Each time you find a value higher than all values you already saw, it means this is the new maximum. 每次您找到的值都比已经看到的所有值高,这意味着这是新的最大值。

You seem to be thinking that max is being compared to i . 您似乎在想将maxi进行比较。 That's not the case. 事实并非如此。 i is being used to loop through the elements of arguments . i被用来遍历arguments的元素。

Lets say that you call findMax like this findMax(1, 2, 3, 4, 5) . 可以说您像这样调用findMax findMax(1, 2, 3, 4, 5) Then arguments is equal to [1, 2, 3, 4, 5] . 然后arguments等于[1, 2, 3, 4, 5]

What happens then is that your for loop will iterate through each of the elements of arguments . 然后发生的是,您的for循环将遍历arguments每个元素。

  • if (arguments[0] > max) is the same as Is 1 > -Infinity? if (arguments[0] > max)与1> -Infinity是否相同? (yes) (是)
  • if (arguments[1] > max) is the same as Is 2 > 1? if (arguments[1] > max)是否等于2> 1? (yes) (是)
  • if (arguments[2] > max) is the same as Is 3 > 2? if (arguments[2] > max)是否等于3> 2? (yes) (是)
  • if (arguments[3] > max) is the same as Is 4 > 3? if (arguments[3] > max)是否等于4> 3? (yes) (是)
  • if (arguments[4] > max) is the same as Is 5 > 4? if (arguments[4] > max)是否等于5> 4? (yes) (是)

Which gives you 5 as the max. 最多给您5。

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

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