我正在学习一些 Node 核心模块,并且我编写了一个小命令行工具来测试 readline
模块但在我的console.log()
上输出,我也收到 undefined
在它下面:/
这是我的代码..
var rl = require('readline');
var prompts = rl.createInterface(process.stdin, process.stdout);
prompts.question("What is your favourite Star Wars movie? ", function (movie) {
var message = '';
if (movie = 1) {
message = console.log("Really!!?!?? Episode" + movie + " ??!?!!?!?!, Jar Jar Binks was a total dick!");
} else if (movie > 3) {
message = console.log("They were great movies!");
} else {
message = console.log("Get out...");
}
console.log(message);
prompts.close();
});
这是我在控制台中看到的内容..
What is your favourite Star Wars movie? 1
Really!!?!?? Episode1 ??!?!!?!?!, Jar Jar Binks was a total dick!
undefined
我为什么要回来undefined
?
最佳答案
Why am I getting back
undefined
?
因为 console.log
没有返回值,所以您将 undefined
分配给 message
。
由于您稍后要输出消息
,因此只需从您设置消息的行中删除console.log
调用即可。例如,改变
message = console.log("Really!!?!?? Episode" + movie + " ??!?!!?!?!, Jar Jar Binks was a total dick!");
至
message = "Really!!?!?? Episode" + movie + " ??!?!!?!?!, Jar Jar Binks was a total dick!";
<小时/>
旁注:您的台词
if (movie = 1) {
将数字 1
分配给movie
,然后测试结果 (1
) 以查看其是否真实。因此,无论您输入什么,它总是会选择该分支。您的意思可能是:
if (movie == 1) {
...尽管我建议不要依赖用户提供的输入的隐式类型强制,因此我会将其放在该回调的顶部附近:
movie = parseInt(movie, 10);
关于javascript - 为什么返回 'Undefined?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14920616/