两个javascript函数不能以相同的方式工作

时间:2016-12-16 08:34:39

标签: javascript

我已经编写了2个javascript函数,但它们的工作方式不同。

console.log(func2());未定义。谁能告诉我为什么以及如何解决这个问题?



function func1()
{
  return {
      bar: "hello"
  };
}

function func2()
{
  return
  {
      bar: "hello"
  };
}

console.log(func1());
console.log(func2());




2 个答案:

答案 0 :(得分:7)

这是因为automatic semicolon insertion从不return之后添加换行符,在您要返回的内容之前,将其视为终止return语句(例如,插入了;return)之后,您的函数最终会有效地返回undefined

答案 1 :(得分:0)

我知道这个。它是分号插入。 func2被翻译为

function func2()
{
  return;
  {
      bar: "hello"
  };
}

并返回undefine