【问题标题】:if statement only executing on index 2 of for loopif 语句仅在 for 循环的索引 2 上执行
【发布时间】:2019-01-22 10:51:27
【问题描述】:

我的咖啡脚本中有这个 for 循环:

compareVersions = (current, minimum) ->
    console.log('current ', current)
    console.log('minimum ', minimum)
    current_parts = current.split '.'
    minimum_parts = minimum.split '.'
    for partIndex in [0..Math.min(current_parts.length, minimum_parts.length)]
       console.log('partIndex ', partIndex)
       if (+current_parts[partIndex] || 0) < (+minimum_parts[partIndex] || 0)
         console.log('current_parts.length1 ', current_parts[partIndex])
         console.log('minimum_parts.length1 ', minimum_parts[partIndex])
         return false
    console.log('PC current_parts.length2 ', current_parts[partIndex])
    console.log('PC minimum_parts.length2 ', minimum_parts[partIndex])
    true

它旨在比较软件版本,如果当前版本低于最低版本,则返回 false。

我添加了console.log 以显示正在发生的事情。

这是我得到的输出。在这种情况下,当前版本高于最小值,但 if 语句仅在索引 2 上执行,在这种情况下,当前版本的数字低于最小值。

current  3.4.1.35
minimum  3.3.3
partIndex  0
partIndex  1
partIndex  2
current_parts.length1  1
minimum_parts.length1  3

if 语句应在 for 循环的每次迭代中执行。有什么问题阻止了这种情况发生?

【问题讨论】:

    标签: javascript for-loop if-statement coffeescript


    【解决方案1】:

    在for循环的每次迭代中都会执行if语句,但是当if语句为真时会打印current_parts.length1和minimum_parts.length1。

    你的 if 语句的执行是:

    3 < 3 false
    4 < 3 false
    1 < 3 true
        print current_parts.length1
        print minimum_parts.length1
    

    如果要显示 current_parts.length1 和 minimum_parts.length1,请将它们放在 if 语句之外,以便在执行 if 语句时看到值。

    【讨论】:

    • 谢谢。通过在 if 之后添加以下内容,我让它按照我想要的方式工作:else if (+current_parts[partIndex] || 0) &gt; (+minimum_parts[partIndex] || 0) return true
    • 我看到你使用的是 else if。考虑只使用else,这样它将采用“>”和“=”条件。
    • 我不希望它包含“=”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2018-02-01
    • 2020-07-17
    相关资源
    最近更新 更多