问题描述
var y = 1;
if(function f(){}){
y += typeof f;
}
console.log(y);
任何人都可以给出有关上述代码的解释的答案吗?
解决方法
是的,这是适当的行为。表达式 function f(){}
将被转换为布尔值。并且会返回真,因为函数总是真。
console.log(Boolean(function f(){}))
现在让我们进入第二部分。为什么 y
是 1undefined
。函数 f
是一个命名函数,它只在它自己的函数体中可见。您尝试访问 f
正文中的 if
,因此无法在那里访问,因此其类型为 "undefined"
console.log(typeof x); //undefined
所以 1 + "undefined" 等于 "1undfined"(1 将转换为字符串并添加到 "undefined")
console.log(1+"undefined")
在您的情况下,该函数是在 if
语句中声明和定义的,该语句是一个块作用域,其作用域仅在这些括号内有效。并且 if 块正在被评估,因为在 JavaScript 中,if
条件中的任何内容都被强制转换为等效的真值或假值,并且对于所有真值执行 if
循环。
var y = 1;
if (function f() {}) { // f has limited scope i.e within the if parenthesis only
y += typeof f; //typeof f is "undefined" and 1+undefined gets concatinated as "1undefined"
}
console.log(y);
但是如果你这样做,你会得到想要的结果:
var y = 1;
let fun=function f(){} //Here the fun has scope outside if statement
if(fun){
y += typeof fun; //type of fun will be function not undefined
}
console.log(y);