【问题标题】:The following Node module returns "undefined", but why?以下节点模块返回“未定义”,但为什么呢?
【发布时间】:2018-11-23 01:57:17
【问题描述】:

下面是一个模块,它接受一个参数,一个数字,然后根据该数字是偶数还是奇数,分别添加或减去一个常量 magicNumber。然而,当我运行这段代码时,我只是得到“未定义”。我究竟做错了什么?

module.exports = (number) => {

    let answer;  //Answer is declared in the global scope
    const magicNumber = 5;  //magicNumber is declared in the global scope

    if (number % 2) {  //If the number is even
        add(number);  //run the number through the add function
    } else {  //otherwise run the number through the subtract function
        subtract(number);
    }

    function add(number){  //Function takes the number as argument, does the math, and returns the value of answer.
        answer = number + magicNumber;
        return answer;
    }

    function subtract(number){  //Function takes the number as argument, does the math, and returns the value of answer.
        answer = number - magicNumber;
        return answer;
    }
};

【问题讨论】:

  • 您的函数没有返回任何内容,因此默认情况下返回值为 undefined(此外,cmets 需要用 /* / */ 分隔,或者在一行中使用//(单独*是行不通的)
  • 你需要从你的函数中返回一些东西,比如return add(number);return subtract(number)
  • 很难理解未显示为代码的代码是否是故意的(例如,第一行“module.exports ...”和最后一行“};”未显示为代码在你的问题中。你的问题还应该包括你用来调用模块的代码。

标签: javascript return return-value node-modules


【解决方案1】:

您导出的块没有返回任何内容,因此默认情况下它是未定义的。

module.exports = (number) => {
let answer;  //Answer is declared in the global scope
const magicNumber = 5;  //magicNumber is declared in the global scope

if (number % 2) {  //If the number is even
    return add(number);  //you should return here as well
} else {  //otherwise run the number through the subtract function
    return subtract(number);//you should return here as well 
}

function add(number){  //Function takes the number as argument, does the math, and returns the value of answer.
    answer = number + magicNumber;
    return answer;
}

function subtract(number){  //Function takes the number as argument, does the math, and returns the value of answer.
    answer = number - magicNumber;
    return answer;
}
};

【讨论】:

  • 我的逻辑是,由于一个或另一个函数 add() 或 subtract() 将不可避免地被分别调用,并且每个函数都有自己的返回,因此代码的预期结果将不可避免地被退回。让我感到困惑的是,当任何一行 add(number); 看起来很直观时,return 语句必须在每一步驱动代码的持续执行。或减去(数字);被击中,这些函数将运行并无论如何都会返回值。我目前正在研究这个,但什么也没找到。我有什么基本的误解吗?
  • 在 JavaScript 和几乎所有编程语言中,return 语句都是基于块的
猜你喜欢
  • 2021-04-25
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
相关资源
最近更新 更多