为什么我在控制台中变得未定义

时间:2018-11-12 14:06:57

标签: javascript

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

我得到的输出为

嘟嘟 未定义

但我不明白为什么会这样

4 个答案:

答案 0 :(得分:6)

您的号角函数不返回任何内容...

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

答案 1 :(得分:3)

return

  

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

您的函数不会返回任何东西。如果某个函数没有返回任何东西,则默认返回undefined

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

答案 2 :(得分:0)

因为您正在执行的操作未返回任何值。

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

应该是这样

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

console.log(horn());

答案 3 :(得分:0)

如果您在undefined函数中返回了内容,则可以删除

horn()

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

相关问题