为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕莱坞森 2021-10-14 10:25:18
我正在学习 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()。有人可以向我解释这种行为的可能原因吗?先感谢您!
查看完整描述

2 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

您会看到这一点,因为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))); //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();


查看完整回答
反对 回复 2021-10-14
  • 2 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信