0

我做了一个函数,用分数的关系减少两个数字。它工作得很好,但问题是它不会返回值。我尝试了各种方法,例如声明一个新变量然后返回它,但它不起作用。我还添加了几个 console.logs 来查看它是否在某个位置停止但什么也没有,它只是没有返回任何东西。

这是我的代码:

function reduceFraction(n, d) {
    var numerator = n;
    var denominator = d;

    if (n % 7 === 0 && d % 7 === 0) {
        numerator /= 7;
        denominator /= 7;
        console.log('Divided by 7');
        reduceFraction(numerator, denominator);
    } else {
        if (n % 5 === 0 && d % 5 === 0) {
            numerator /= 5;
            denominator /= 5;
            console.log('Divided by 5');
            reduceFraction(numerator, denominator);
        } else {
            if (n % 3 === 0 && d % 3 === 0) {
                numerator /= 3;
                denominator /= 3;
                console.log('Divided by 3');
                reduceFraction(numerator, denominator);
            } else {
                if (n % 2 === 0 && d % 2 === 0) {
                    numerator /= 2;
                    denominator /= 2;
                    console.log('Divided by 2');
                    reduceFraction(numerator, denominator);
                } else {
                    console.log('Was not divided by anything');
                    var reduced = numerator + "/" + denominator;
                    return reduced; //console.log(numerator + "/" + denominator); logs 1/18
                }
            }
        }
    }
}
reduceFraction(3, 54);

我不知道嵌套一堆 if 语句是否必须对它做任何事情,但这是目前(我能想到的)它会减少一小部分的唯一方法......在此先感谢。

4

2 回答 2

3

在递归函数中,您也需要return

替换所有

    reduceFraction(numerator, denominator);

像这样 :

    return reduceFraction(numerator, denominator);
于 2013-10-26T19:59:01.833 回答
0

你必须退回

 function reduceFraction(n, d) {
    var numerator = n;
    var denominator = d;

    if (n % 7 === 0 && d % 7 === 0) {
        numerator /= 7;
        denominator /= 7;
        console.log('Divided by 7');
        return reduceFraction(numerator, denominator);
    } else {
        if (n % 5 === 0 && d % 5 === 0) {
            numerator /= 5;
            denominator /= 5;
            console.log('Divided by 5');
            return reduceFraction(numerator, denominator);
        } else {
            if (n % 3 === 0 && d % 3 === 0) {
                numerator /= 3;
                denominator /= 3;
                console.log('Divided by 3');
                return reduceFraction(numerator, denominator);
            } else {
                if (n % 2 === 0 && d % 2 === 0) {
                    numerator /= 2;
                    denominator /= 2;
                    console.log('Divided by 2');
                    return reduceFraction(numerator, denominator);
                } else {
                    console.log('Was not divided by anything');
                    var reduced = numerator + "/" + denominator;
                    return reduced; //console.log(numerator + "/" + denominator); logs 1/18
                }
            }
        }
    }
}
return reduceFraction(3, 54);
于 2013-10-26T20:00:18.700 回答