【发布时间】: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