【问题标题】:How can I make my if-else statement work如何使我的 if-else 语句起作用
【发布时间】:2017-01-18 17:03:09
【问题描述】:

我的函数采用一个整数除数数组、一个low 数字和一个high 数字作为参数。它打印lowhigh 数字之间的范围。

  • 如果范围内的数字可以被数组的所有元素整除,则打印“all match”。
  • 如果至少有一个数字匹配,则打印“one match”。
  • 如果没有数字匹配,则打印该数字。

但是,我不知道如何正确编写 if-else 语句。它只打印匹配的数字。当我更改 else-if 语句时,它会将所有数字打印两次。

function allFactors(factors, num){
          var nums = [];
          for(var i = 0; i < factors.length; i++) {
            var factor = factors[i];
            if(num % factor === 0){
              nums.push(factor);
            }
          }
          if(nums.length === factors.length){
            return true;
          }
          return false;
        }

        //console.log(allFactors([2,3],6))

        function isFactor(num, factor) {
          if(num % factor === 0) {
            return true;
          }
          return false;
        }

        function matches(factors, low, high) {
          var skipper = false
            for(var i = low; i <= high; i++) {
              if(allFactors(factors,i)){
                console.log(i + " match_all")
              } else {
              for(var j = 0; j < factors.length;j++) {
                var factor = factors[j];

                if(isFactor(i,factor)) {
                  console.log(i + " match_one");
                  skipper = true
                } else {
                  if(isFactor(i,factor)) {continue}
                  console.log(i)
                }
              }

              }
            }
        }


        matches([2,3],1,6)

【问题讨论】:

  • 这行skipper = true是做什么的?
  • 我在想,当第二个 if 语句为真时,我是否可以让它为真,那么我可以让它不打印,但它仍然会打印

标签: javascript if-statement


【解决方案1】:

一旦知道 One factor 匹配,请尝试打破循环。

function matches(factors, low, high) {    
    var skipper = false;

    for(var i = low; i <= high; i++) {

        if(allFactors(factors,i)){
            console.log(i + " match_all")
        } else {

            for(var j = 0; j < factors.length;j++) {
                var factor = factors[j];

                if(isFactor(i,factor)) {

                    console.log(i + " match_one");
                    skipper = true;

                    // break here because we know that at least one factor matches
                    // and print "match_one"
                    break;
                } else {

                    // number not matched
                    console.log(i);
                }
            }
        }

        // use skipper variable you assigned above to break out of outer loop
        if(skipper){
            break;
        }
    }
}

【讨论】:

  • 仍然没有 bueno 只计算到​​数字 2 然后返回 d=对于任何一组数字这个问题真的难倒我
  • 检查我的编辑,if continue; 周围的声明是没用的。你在检查if( 5 &gt; 7 ){ } else { if(5 &gt; 7) { continue; } }
猜你喜欢
  • 2014-03-21
  • 2022-11-15
  • 1970-01-01
  • 2023-03-13
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多