为什么这回归'未定义?'

时间:2013-02-17 11:34:03

标签: javascript macos node.js readline

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

2 个答案:

答案 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