我的函数采用整数的除数数组,low
数字和high
数字作为参数。它打印的范围介于low
和high
之间。
但是,我无法弄清楚如何正确编写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)
答案 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;
}
}
}