如何使我的if-else语句有效

时间:2017-01-18 17:03:09

标签: javascript if-statement

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

  • 如果范围内的数字可被数组的所有元素整除,则打印“all 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)

1 个答案:

答案 0 :(得分:0)

一旦您知道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;
        }
    }
}