Javascript 如何使用for循环在看不见的数组中查找最大数?

Javascript 如何使用for循环在看不见的数组中查找最大数?,javascript,arrays,for-loop,Javascript,Arrays,For Loop,这就是问题的解决办法。我不明白的是,为什么不是“if(I>currentMax)”?我也不明白数字[I]的本质。我知道我们可以引用数组中的索引来执行数字[0],但数字[I]让我感到困惑 function max(numbers) { let currentMax = numbers[0]; for (let i = 0; i < numbers.length; i++) { if (numbers[i] > currentMax) { currentMa

这就是问题的解决办法。我不明白的是,为什么不是“if(I>currentMax)”?我也不明白数字[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;
}
函数最大值(数字){
设currentMax=number[0];
for(设i=0;icurrentMax){
currentMax=数字[i];
}
}
返回电流最大值;
}

numbers[i]
指存储在位置
i
的值。如果要使用
If(i>currentMax)
则始终返回最后一个元素,因为最后一个元素始终具有最大的索引


不要重新发明轮子,使用数学。max(…number)在这种情况下,
i
是一个“索引”,允许我们迭代数组中的所有位置(并访问它们的值)。在这种情况下,
i=0
i=1
,…,
i=number.length

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


如果您询问
If(i>currentMax)
您将“index”(
i
)的值与
currentMax
值进行比较。如果您想从数字数组中返回最大值,这是不正确的。

假设您有一个如下数组:

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

函数最大值(数字){
设currentMax=number[0];
for(设i=0;icurrentMax){
currentMax=数字[i];
log(“新currentMax:,currentMax”)
}
}
返回电流最大值;
}

max([1,2,4,2])
正如您所说,您可以通过执行数字来引用数组中的索引。您可以使用以数字作为值的变量,而不是硬编码数字

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;
}
函数最大值(数字){
//获取数组中第一位的值
设currentMax=number[0];
//创建一个名为i的变量
//将其设置为0
//循环,每次增加i,只要i小于数组的长度
//第一次通过i=0
//第二次通过i=1
//那么i=2
//…重复到最后
for(设i=0;icurrentMax){
//然后将当前最大值设置为它
currentMax=数字[i];
}
}
//返回电流最大值
返回电流最大值;
}

Math.max(…numbers)
numbers[i]与您的示例中的数字[0]完全相同。它位于for循环中,其中我将成为一个从0到最大长度的数字。因此每次执行循环时,它将是数字[0],然后是数字[1]因此,在重新阅读您的问题之后,您似乎需要进行一些阅读,以了解什么是
i
,以及为什么它会被如此使用。@mhodges OP在某个地方发现了这段代码,它可以做他想要做的事,但他不知道为什么……同意您的观点,即他需要学习一门语言lot@LelioFaieta是的,这就是我为什么发帖子的原因链接。我一开始误解了这个问题,我以为它是在问如何在不使用循环的情况下找到最大值。重新发明轮子是很有用的,特别是在学习事物如何工作时。我不会把
I
称为指针。这可能会误导人,因为它不指向内存中的某个位置;它只是一个用作索引的整数@bstrauch24但这是一个稍微相关的概念,我不认为这是一个问题