【发布时间】:2018-11-23 01:57:17
【问题描述】:
下面是一个模块,它接受一个参数,一个数字,然后根据该数字是偶数还是奇数,分别添加或减去一个常量 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;
}
};
【问题讨论】:
-
您的函数没有返回任何内容,因此默认情况下返回值为
undefined(此外,cmets 需要用/*/*/分隔,或者在一行中使用//(单独*是行不通的) -
你需要从你的函数中返回一些东西,比如
return add(number);和return subtract(number) -
很难理解未显示为代码的代码是否是故意的(例如,第一行“module.exports ...”和最后一行“};”未显示为代码在你的问题中。你的问题还应该包括你用来调用模块的代码。
标签: javascript return return-value node-modules