2013-02-17 118 views
0

我正在学习一些节点核心模块,我已经写了一个小的命令行工具来测试出readline模块,但在我的console.log()输出,我也recieving 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(); 
}); 

这里还有什么IM在我的控制台看到..

What is your favourite Star Wars movie? 1 
Really!!?!?? Episode1 ??!?!!?!?!, Jar Jar Binks was a total dick! 
undefined 

为什么我找回undefined

+2

你认为它是什么? – JJJ 2013-02-17 11:37:45

回答

4

为什么我回来undefined

因为console.log没有返回值,所以你要指定undefinedmessage

由于您稍后要输出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) { 

受让人人数1movie,然后测试结果(1)至看看它是否真实。所以无论你输入什么内容,它都会采用该分支。你大概的意思是:

if (movie == 1) { 

...虽然我会建议依靠用户提供的输入的隐含类型转换,所以我把这个附近是回调的顶部:

movie = parseInt(movie, 10); 
+0

@mplungjan:的确值得注意。 – 2013-02-17 11:57:38

+0

哈,derp ..当然..我也是console.log的消息内容本身被分配了一个console.log语句! 我的代码现在读取下面,它很好。 var rl = require('readline'); var prompts = rl.createInterface(process.stdin,process.stdout); prompts.question( “什么是你最喜欢的星球大战电影?”,功能(电影){ \t如果(电影= 1){ \t \t的console.log( “真的!?!??插曲” +电影+“??!?!!?!?!,罐子瓶子是一个完整的家伙!“); \t}否则,如果(电影> 3){ \t \t的console.log(” 他们是伟大的电影! “); \t}其他{ \t \t的console.log(” 滚出去......” ); \t}; prompts.close(); }); – Keva161 2013-02-17 12:13:30

1

console.log不返回一个值,所以结果是undefined

注意:使用==进行比较,例如:movie == 1

相关问题