猿问

变量作用域相关。从不同的函数调用函数中的变量 - 意外的行为/结果

我正在学习 javascript,我偶然发现了这种行为,它不会在代码末尾执行函数 f2()。


function f1() {

  var oneT = 55;

  console.log(oneT);

}

f1();

console.log(typeof(oneT));


function f2() {

  if (typeof(oneT) == undefined) {

    console.log("oneT can't be read outside the f1() as it's scope is limited to the fn f1().");

  }

}

f2();

如果undefined没有放在 " " 中,那么最后的 f2() 将被跳过(被忽略?)。如果放入“”,则执行 f2()。有人可以向我解释这种行为的可能原因吗?先感谢您!


慕莱坞森
浏览 127回答 2
2回答

jeck猫

您会看到这一点,因为typeof运算符将值"undefined"作为string返回给您。来自 MDN文档:typeof 运算符返回一个字符串,指示未计算的操作数的类型。您可以typeof()在上面执行 atypeof(typeof(oneT))来检查它是否确实向您返回了一个字符串。在f2()获取调用,但你看不到任何输出作为if块被完全忽略,因为你是一个比较字符串"undefined"从返回typeof(oneT)与undefined价值:function f1() {  var oneT = 55; //function scope  console.log(oneT);}f1();console.log(typeof(typeof(oneT))); //stringfunction f2() {  if (typeof(oneT) == undefined) { //false and if is skipped     console.log("oneT can't be read outside the f1() as it's scope is limited to the fn f1().");  }  console.log("Inside f2"); //prints this}f2();function f3() {  if (typeof(oneT) === "undefined") { //true     console.log("oneT can't be read outside the f1() as it's scope is limited to the fn f1().");  }}f3();
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答