0

我正在学习一些节点核心模块,并且我已经编写了一个小命令行工具来测试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

4

2 回答 2

5

我为什么要回来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);
于 2013-02-17T11:35:48.807 回答
1

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

注意:比较是用 完成的==,例如:movie == 1

于 2013-02-17T11:35:47.377 回答