【问题标题】:Why I am getting undefined in console [duplicate]为什么我在控制台中变得不确定[重复]
【发布时间】:2019-04-15 06:34:54
【问题描述】:

const horn = () => {
  console.log("Toot");
};
console.log(horn());

我得到的输出为

嘟嘟 未定义

但我不明白为什么会这样

【问题讨论】:

  • 因为您正在记录 horn 的结果,这没什么 /undefined

标签: javascript


【解决方案1】:

return

如果省略该值,则返回 undefined。

你的函数没有返回任何东西。如果一个函数没有返回任何东西,那么默认返回undefined

const horn = () => {
  console.log("Toot");
  return "Toot";
};
console.log(horn());

【讨论】:

    【解决方案2】:

    你的喇叭函数没有返回任何东西......

    const horn = () => {
      return 'horn';
    };
    const horn2 = () => {
      console.log('horn');
    };
    console.log(horn());
    horn2();

    【讨论】:

      【解决方案3】:

      如果您在horn() 函数中返回某些内容,则可以删除undefined

      const horn = () => {
            return "Toot";
          };
      console.log(horn());

      【讨论】:

        【解决方案4】:

        因为你的函数没有返回任何值。

        const horn = () => {
          console.log("Toot");// <-- problem
        };
        

        应该是这样的

        const horn = () => {
          return "Toot";
        };
        

        console.log(horn());

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-13
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-09
          相关资源
          最近更新 更多