gpt4 book ai didi

javascript - 无法理解此 JavaScript 代码的输出

转载 作者:行者123 更新时间:2023-11-28 15:15:10 26 4
gpt4 key购买 nike

为什么下面的代码会打印undefined?此外,在删除 if block 后,它会打印 hello there 作为输出。

var message = "hello there!";

function hello(){
console.log(message);

if (true) {
var message = "wassup?!";
}
}

hello();

最佳答案

这就是所谓的“提升”。来自 the Mozilla docs (强调):

Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

var message if内声明 block 隐藏全局message函数内所有代码的变量,包括对 console.log() 的调用.

还有两点。首先,JavaScript 将变量声明与变量初始化分开。这就是为什么本地 messageconsole.log(message) 时,变量具有未定义的值执行,而不是 "wassup?!" 。其次,由于提升是一种违反直觉的行为(至少对于习惯其他语言的程序员来说),因此大多数 JavaScript linting 工具都会向您发出关于 var 的警告。不在其执行上下文开始处的语句。我强烈建议您找到一个 linting 工具(例如 JSLint、JSHint、ESLint 和 JSCS)并使用它。

关于javascript - 无法理解此 JavaScript 代码的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34326972/

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