【问题标题】:Result of the typeof name of function, inside if condition函数名称类型的结果,在 if 条件内
【发布时间】:2023-01-30 13:37:42
【问题描述】:

我想知道为什么 if 条件中函数的 typeof 名称的结果为“未定义”。

如果我尝试使用此代码获取函数名称的类型,我会收到结果“函数”。

function calc(){}

console.log(typeof calc); //The result is "function"

但是,如果我尝试将函数放入 if 条件中,我会收到结果“未定义”。

if(function calc(){}) {
  y = typeof calc;
}

console.log(y); //The result is "undefined"

该函数如何在 if 条件下工作以及为什么 typeof 的结果是“未定义”?

如果我尝试获取任何其他字符串的类型,我会收到相同的结果

if(function calc(){}) {
  y = typeof z;
}

console.log(y); //The result is "undefined"
if(function calc(){}) {
  y = typeof nothing;
}

console.log(y); //The result is "undefined

我知道变量的默认值是“undefined”,不返回任何值的函数的结果是“undefined”,但我可以理解它在 if 条件下是如何工作的,以及为什么结果是“undefined” .

【问题讨论】:

    标签: javascript


    【解决方案1】:

    答案很明确,你没有定义 y 变量,所以 y 是未定义的,不是 typeof calc

    并且您需要在 if 范围之外定义 calc 函数

    像这样 :

    let y;
    
    function calc(){}
    
    
    if(calc){
       y = typeof calc;
    }
    
    console.log(y)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多