JavaScript函数不返回任何内容

时间:2013-10-26 19:57:21

标签: javascript return

我做了一个函数,用分数关系减少两个数。它完美地工作但问题是它不会返回值。我尝试过各种各样的事情,例如声明一个新变量然后返回它,但它不起作用。我还添加了一些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语句是否必须对它做任何事情,但这是唯一的方法(我能想到的)现在它会减少一小部分......提前谢谢。

2 个答案:

答案 0 :(得分:3)

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

替换所有

    reduceFraction(numerator, denominator);
像这样:

    return reduceFraction(numerator, denominator);

答案 1 :(得分: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);