繁体   English   中英

我如何使if-else语句起作用

[英]How can I make my if-else statement work

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

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

但是,我不知道如何正确编写我的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)

一旦知道一个因素匹配,就尝试打破循环。

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;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM