猿问

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

此函数返回数组中的最大数。我需要帮助来理解 if 部分:if (arr[i] > maxNumber) {maxNumber = arr[i]}。使用伪代码或解释这究竟是如何工作的?


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]));


拉风的咖菲猫
浏览 88回答 2
2回答

紫衣仙女

function max(array) {&nbsp; &nbsp; largest number is equal to 0;&nbsp; &nbsp; for (i is equal to 0; i is less than the length of array; increment i by 1 each time) {&nbsp; &nbsp; &nbsp; &nbsp; if (the item at the current index is greater than the previous largest number) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set the largest number to to the item at the current index;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return largest number which will be 0 if no larger number is found}值得注意的是,如果数组中的所有值都是负数,它将返回 0;这也适用于负数。function max(arr){&nbsp; &nbsp; let maxNumber = -Infinity&nbsp; &nbsp; for (i = 0; i < arr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (arr[i] > maxNumber){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxNumber = arr[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return maxNumber}

桃花长相依

这部分:if (arr[i] > maxNumber) {maxNumber = arr[i]}做的是检查当前数组成员是否大于当前 maxNumber 以及它是否正在将 maxNumber 值更改为当前数组。简而言之,max(whatEverArray)将始终返回零或数组的最大值。如果它返回零,则意味着所有数组值都为零或小于零。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答