2 回答
TA贡献1839条经验 获得超15个赞
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
}
值得注意的是,如果数组中的所有值都是负数,它将返回 0;这也适用于负数。
function max(arr){
let maxNumber = -Infinity
for (i = 0; i < arr.length; i++) {
if (arr[i] > maxNumber){
maxNumber = arr[i]
}
}
return maxNumber
}
TA贡献1860条经验 获得超8个赞
这部分:if (arr[i] > maxNumber) {maxNumber = arr[i]}
做的是检查当前数组成员是否大于当前 maxNumber 以及它是否正在将 maxNumber 值更改为当前数组。
简而言之,max(whatEverArray)
将始终返回零或数组的最大值。如果它返回零,则意味着所有数组值都为零或小于零。
添加回答
举报