【问题标题】:Why is same return type but result is difference [duplicate]为什么返回类型相同但结果不同[重复]
【发布时间】:2016-08-30 22:57:05
【问题描述】:

我在 java 脚本中有两个返回类型相同的函数,但返回类型不同。下面截图id的使用代码

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

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

调用函数..

console.log("foo1 returns:");
console.log(foo1());
console.log("foo2 returns:");
console.log(foo2());

输出结果 ....

foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined 

【问题讨论】:

  • 你能提供完整的代码而不是一小部分吗?
  • @Darshit 这是完整的代码。
  • @Konst 请不要建议对代码进行这样的编辑,除非您完全了解所有后果 - 您所做的更改会导致问题消失。
  • 是的@JamesThorpe 可能是关于 ASI 的问题。这可以帮助你stackoverflow.com/questions/2846283/…

标签: javascript console console.log


【解决方案1】:

它在此处自动插入分号。其余代码永远不会到达。

function foo2()
{
  return    // get a automatic semicolon insert here
  {
      bar: "hello"
  };
}

请看:Warning: unreachable code after return statement

【讨论】:

    【解决方案2】:

    那是因为 JavaScript 会解释

    return
    {
        bar: "hello"
    };
    

    as return 语句后跟块创建(在运行时被忽略)。不像“返回一个对象”。而且我真的不知道为什么 JavaScript 开发人员会做出这样的决定。

    无论如何,ASI 在return 之后插入; 导致等效代码:

    return;
    {
        bar: "hello"
    };
    

    return 之后的换行符是罪魁祸首。如果您想退货,请勿使用它。

    【讨论】:

      【解决方案3】:

      一个没有分号的免费javascript,但它会自动添加一个分号,这就是为什么你会得到未定义的Refer this

      function foo1()
          {
            return {
                bar: "hello"
            };
          }
      
          function foo2()
          {
            return{
                bar: "hello"
            };
          }
          console.log("foo1 returns:");
          console.log(foo1());
          console.log("foo2 returns:");
          console.log(foo2()); 
      

      【讨论】:

        猜你喜欢
        • 2017-04-01
        • 2018-02-17
        • 1970-01-01
        • 2012-07-28
        • 2013-03-10
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 2017-10-17
        相关资源
        最近更新 更多