JavaScript while 循环在 var 声明之前接受条件

JavaScript while loop accepts condition before var declaration

令我惊讶的是以下代码有效:

while(fred !== "stop"){
    var fred = prompt("Should I stop or go?")
};

我会在 do while 循环中理解这一点:

do {
    code to be executed at least once
​}
while (condition);

JavaScript如何在函数将 fred 声明为变量之前设置条件?

我读过的其他问题与 var 声明有关 条件中。

在声明 fred 之前,fredundefined,所以 undefined !== "stop",这是真的。

JavaScript 在用 var 声明变量时有点奇怪;它们在函数范围内声明,而不是像其他语言一样在块范围内声明。如果你的函数中有一个 var,在任何地方,最后声明被拉到开头(不是实例化);所以你的代码变成:

function () {
    var fred;
    while(fred !== "stop"){
        fred = prompt("Should I stop or go?")
    };
}

刚声明时,变量就存在,并接收到undefined的值。如果您想要更合理的块范围变量,请使用 let/const。然后你会得到你期望的行为。

来自Mozilla documentation

Variable declarations, wherever they occur, are processed before any code is executed.

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

和一个警告:

It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached: