如何使用 for 循环在看不见的数组中找到 MAX 数?



这是问题的解决方案。我不明白的是为什么不是"如果(我>当前Max)?我也不明白数字的本质[i]。我知道我们可以在数组中引用索引做数字[0],但是数字[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).

假设你有一个数组,如下所示:

[1, 2, 4, 2]

这首先设置currentMaxnumbers[0]哪个是一个。然后它一次循环一个元素遍历数组。如果它在循环中找到一个更大的数字——换句话说if (numbers[i] > currentMax)那么它会currentMax该数字设置。例如,当i等于 2 和 4 时,这将在循环中第二次和第三次发生。但它不会在最后一次通过循环发生。观察这种情况发生的一种简单方法是在控制台运行时将一些内容打印到控制台:

function max(numbers) {
let currentMax = numbers[0];
for (let i = 0; i < numbers.length; i++) {
console.log("i:", i, "element:", numbers[i], "max:", currentMax)
if (numbers[i] > currentMax) {
currentMax = numbers[i];
console.log("new currentMax:", currentMax)
}
}
return currentMax;
}
max([1, 2, 4, 2])

在这种情况下,i是一个"索引",它允许我们迭代数组中的所有位置(并访问它们的值)。在这种情况下i=0i=1,...,i=numbers.length

if (numbers[i] > currentMax)询问存储在位置i数组中的数字是否大于currentMax值。这保证了从提供的数组中返回最大数量

如果你问if (i > currentMax)你比较"索引"(i)的值和currentMax值的值。如果要从数字数组中返回最大值,则这是不正确的。

就像你说的,你可以通过做数字来引用数组中的索引。您可以使用具有数字作为值的变量,而不是硬编码数字。

function max(numbers) {
// get the value in the first place in the array  
let currentMax = numbers[0];
// create a variable called i
// set it to 0
// loop through, increasing i each time, for as long as i is less than the length of the array
// the first time through i = 0
// the second time through i = 1
// then i = 2
// ... repeat until the end
for (let i = 0; i < numbers.length; i++) {
// get the value from the array at the i place
// if it is greater than the current max
if (numbers[i] > currentMax) {
// then set current max to it
currentMax = numbers[i];
}
}
// return current max
return currentMax;
}

最新更新