首页 > 解决方案 > 变量范围相关。从不同的函数调用函数中的变量 - 意外的行为/结果

问题描述

我正在学习 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();

如果未定义未放在“”中,则跳过末尾的 f2()(忽略?)。如果放入“”,则执行 f2()。有人可以向我解释这种行为的可能原因吗?先感谢您!

标签: javascript

解决方案


您会看到这一点,因为typeof操作员将值"undefined"作为字符串返回给您。

来自 MDN文档

typeof 运算符返回一个字符串,指示未计算的操作数的类型。

您可以执行 a typeof()on typeof(typeof(oneT))to 检查它是否确实返回了一个字符串。

f2()调用,但您看不到任何输出,因为该if块被完全跳过,因为您正在比较"undefined"从返回的字符串typeof(oneT)undefined值:

function f1() {
  var oneT = 55; //function scope
  console.log(oneT);
}

f1();
console.log(typeof(typeof(oneT))); //string

function 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();


推荐阅读