以下Node模块返回“ undefined”,但是为什么呢?

时间:2018-11-23 01:57:18

标签: javascript return return-value node-modules

下面是一个模块,该模块接受一个参数,一个数字,然后分别根据数字是偶数还是奇数从中添加或减去const magicNumber。但是,当我运行此代码时,我只会得到“未定义”。我究竟做错了什么?

module.exports = (number) => {

    let answer;  //Answer is declared in the global scope
    const magicNumber = 5;  //magicNumber is declared in the global scope

    if (number % 2) {  //If the number is even
        add(number);  //run the number through the add function
    } else {  //otherwise run the number through the subtract function
        subtract(number);
    }

    function add(number){  //Function takes the number as argument, does the math, and returns the value of answer.
        answer = number + magicNumber;
        return answer;
    }

    function subtract(number){  //Function takes the number as argument, does the math, and returns the value of answer.
        answer = number - magicNumber;
        return answer;
    }
};

1 个答案:

答案 0 :(得分:2)

您导出的块未返回任何内容,因此默认情况下未定义。

tl;dr