【问题标题】:Why the output is not logic?为什么输出不是逻辑?
【发布时间】:2018-07-28 14:26:33
【问题描述】:

let vacationSpots = ['USA', 'UK', 'Colombia']; 

 for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex >=  0; vacationSpotIndex-- ) {
   console.log('I would love to visit '  + vacationSpots[vacationSpotIndex]);
 }

我假设长度是 3,我们减去 1 等于 2; 所以索引开始是 2,我们在每个循环上减去 1 条件问题 假期点索引 >= 0 我想在逻辑上它是vacationSpotIndex

【问题讨论】:

  • 预期输出是什么?
  • 你到底在问什么?
  • 请花几分钟时间阅读How to Ask,帮助我们帮助您。你真的没有解释你的问题,或者你期望这段代码做的事情与现在做的不同
  • “我想逻辑上是vacationSpotIndex <= 0 — 不,不是。阅读docs on for loops。条件vacationSpotIndex <= 0 将导致循环永远不会执行,因为索引不能为负数。
  • 他的条件是检查一个没有数组的整数。所以,没有索引。仅仅因为它具有名称“索引”并不意味着它是数组的索引。它是一个整数。

标签: javascript for-loop


【解决方案1】:

我可能是错的,但您的问题似乎是,为什么是vacationSpotIndex >= 0 而不是vacationSpotIndex <= 0?答案是,在循环的每次迭代之前都会检查 for 循环的条件。你的意思是,“运行这个循环只要 vacationSpotIndex >= 0。”一旦该条件不再成立,循环将停止运行。所以它会倒数2、1、0、-1,然后因为-1不大于等于0,循环就会停止。

【讨论】:

  • 你的回答和我的回答有什么不同
  • @Osama 您的代码省略了数组的第一项。 OP的代码是正确的(我认为,问题不是很清楚)。我以为 OP 只是在寻找它为什么起作用的解释,这就是我的回答。
【解决方案2】:

javaScript中数组的索引从0开始

一切正常。这里没有错。

let vacationSpots = ['USA', 'UK', 'Colombia']; 
    vacationSpots.length=3
    index->0='USA'
    index->1='UK'
    index-2='Colombia'

for (let holidaySpotIndex = holidaySpots.length - 1; holidaySpotIndex >= 0; holidaySpotIndex-- ) {

vacationSpotIndex >= 0; 这个条件说迭代循环直到vacationSpotIndex大于或等于零,并且在每次迭代之前检查。

循环将从 index=2 开始,直到 index=0

vacationSpotIndex=2
vacationSpotIndex=1
vacationSpotIndex=0

【讨论】:

    【解决方案3】:

    当您使用 >=0 时,它会在它为 0 时继续循环,因此导致超出范围 (-1) 使其仅 >0

    let vacationSpots = ['USA', 'UK', 'Colombia']; 
     for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex > 0; vacationSpotIndex-- ) {
       console.log('I would love to visit '  +        vacationSpots[vacationSpotIndex]);
      }
    

    【讨论】:

    • 当 =0 然后 0-1 然后是vacationSpots[-1]时会循环
    • 答案毫无意义
    猜你喜欢
    • 2020-05-15
    • 1970-01-01
    • 2010-09-28
    • 2010-09-26
    • 2011-09-07
    • 2023-01-29
    • 1970-01-01
    • 2011-10-30
    • 2018-10-20
    相关资源
    最近更新 更多