javascript - 变量范围相关。从不同的函数调用函数中的变量 - 意外的行为/结果
问题描述
我正在学习 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()。有人可以向我解释这种行为的可能原因吗?先感谢您!
解决方案
您会看到这一点,因为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();
推荐阅读
- asp.net - 使用 GraphServiceClient 检索 Azure 广告成员的组信息
- azure-web-app-service - 允许 Azure Web App 访问 VM 上的数据库,而无需将该 VM 暴露给外界
- css - 如何在一个 flexbox 中上下对齐项目?
- python - Python Capn Proto:恢复者?
- kubernetes - 使用补丁从节点中删除标签
- java - 通过方法调用打印数组
- python - 将带有日期列的 Pandas 数据框转换为 Vaex 数据框
- python - 使用 np.reshape 时元组索引超出范围错误
- node.js - 如何将多张图片上传到 Cloudinary?
- javascript - 如何选择字符串指定部分左侧的字符串值,不包括空格?