我正在学习一些节点核心模块,我已经编写了一个小命令行工具来测试readline
模块,但在我的console.log()
输出上,我也接受了{{1在它下面:/
这是我的代码..
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
?
答案 0 :(得分:4)
为什么我会回来
undefined
?
由于console.log
没有返回值,因此您要将undefined
分配给message
。
由于您稍后输出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
分配<{1}}到movie
,然后测试结果(1
)以查看它是否真实。所以不管你输入什么内容,它总会占用那个分支。你可能意味着:
if (movie == 1) {
...虽然我建议不依赖于用户提供的输入的隐式类型强制,所以我把它放在该回调的顶部附近:
movie = parseInt(movie, 10);
答案 1 :(得分:1)
console.log
未返回值,因此结果为undefined
。
注意:与==
进行比较,例如:movie == 1
。