当我的console.log类型的函数返回一个对象时,它的类型为undefined。我不明白为什么

时间:2018-06-26 17:20:23

标签: javascript

我不明白为什么这段代码的结果不确定?

function f() {
    return
    {
        x: 0
    };
}
console.log(type of f());

1 个答案:

答案 0 :(得分:1)

typeof是一个单词。另外,您正在调用函数,因此您正在评估它的返回值,由于自动分号插入,该值在代码中未定义。

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

  

return语句受自动分号插入(ASI)的影响。 return关键字和表达式之间不允许使用行终止符。

function f() {
    return //this is treated as though it had a ;
    {
        x: 0
    };
}
console.log(typeof f());
console.log(typeof f);

function f() {
    return {
        x: 0
    };
}
console.log(typeof f());
console.log(typeof f);