简体   繁体   English

有人可以解释这个 for 循环是如何工作的吗?

[英]Can someone explain how this for loop works?

This function returns the largest number from an array.这个 function 返回数组中的最大数字。 I need help on understanding the if part: if (arr[i] > maxNumber) {maxNumber = arr[i]} .我需要帮助来理解 if 部分: if (arr[i] > maxNumber) {maxNumber = arr[i]} Using pseudocode or an explanation how exactly does this work?使用伪代码或解释这究竟是如何工作的?

 function max(arr){ let maxNumber = 0 for (i = 0; i < arr.length; i++) { if (arr[i] > maxNumber){ maxNumber = arr[i] } } return maxNumber } console.log(max([1,2,3,40,5]));

function max(array) {
    largest number is equal to 0;
    for (i is equal to 0; i is less than the length of array; increment i by 1 each time) {
        if (the item at the current index is greater than the previous largest number) {
            set the largest number to to the item at the current index;
        }
    }
    return largest number which will be 0 if no larger number is found
}

Worth noting that if all values in the array are negative, it will return 0;值得注意的是,如果数组中的所有值都是负数,它将返回 0; This will work for negative numbers too.这也适用于负数。

function max(arr){
    let maxNumber = -Infinity
    for (i = 0; i < arr.length; i++) {
        if (arr[i] > maxNumber){
            maxNumber = arr[i]
        }
    }
    return maxNumber
}

What this part: if (arr[i] > maxNumber) {maxNumber = arr[i]} doing is checking if the current array member is greater than the current maxNumber and if it is changing the maxNumber value to the current array.这部分的内容: if (arr[i] > maxNumber) {maxNumber = arr[i]}正在检查当前数组成员是否大于当前 maxNumber 以及它是否正在将 maxNumber 值更改为当前数组。

In short, max(whatEverArray) will always return zero or the biggest value of the array.简而言之, max(whatEverArray)将始终返回零或数组的最大值。 and if it return zero, means all the array values are either zero or less than zero.如果它返回零,则意味着所有数组值都为零或小于零。

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

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