gpt4 book ai didi

javascript - 我不明白为什么控制台显示未定义

转载 作者:行者123 更新时间:2023-11-28 14:11:04 24 4
gpt4 key购买 nike

我是编码新手,无法弄清楚以下代码。如果有人能帮助我,我将不胜感激!!

function a() {
function b() {
console.log(x);
}
var x = 2;
b();
}
var x = 1;
a();

当我运行这段代码时,控制台是 2 是完全合理的。 。 super !

但是当我运行这段代码时:

function a() {
b();

function b() {
console.log(x);
}
var x = 2;
}
var x = 1;
a();

当这段代码运行时,我本以为控制台的答案是 2还有!但我得到 undefined作为答案。至少我会认为1如果它不是 2,则可能是答案,但永远不会:undefined .

有人可以帮我吗?

非常感谢!

最佳答案

var 声明被提升。

这意味着这些声明在编译时(在代码运行之前)被移动到当前作用域(函数)的顶部。

提升移动变量声明,但不会移动变量赋值

因此,这段代码:

doSomething();
var variable = value; //Declaration with assignment

转换为:

var variable; //Declaration
doSomething();
variable = value; //Assignment

因此,您的代码与以下代码相同:

function a() {
var x; //x is now undefined

//Function declarations are hoisted as well:
function b() {
console.log(x);
}

b(); //x is still undefined now...

x = 2; //x is now 2, but your console.log has already run.
}
var x = 1; //This line doesn't affect your code, as the x you log is in different scope, and the internal x shadows this one.
a();

关于javascript - 我不明白为什么控制台显示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59429773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com