2013-02-17 113 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

相關問題