这就是问题的解决方案。我不明白的是为什么它不是“if ( i > currentMax)”?我也不明白 numbers[i] 的本质。我知道我们可以引用数组中的索引做 numbers[0],但是 numbers[ i] 让我感到困惑。
function max(numbers) {
let currentMax = numbers[0];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > currentMax) {
currentMax = numbers[i];
}
}
return currentMax;
}
最佳答案
numbers[i]
指的是存储在位置 i
的值。如果您要使用 if (i > currentMax)
,那么您将始终返回最后一个元素,因为最后一个元素始终具有最大索引。
不要重新发明轮子,使用 Math.max(...numbers)
。
关于javascript - 如何使用for循环在看不见的数组中找到最大数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51598428/