为何这种奇怪的行为?

Pau*_*han 10 javascript

我正在以三种方式修改一段代码.在这3个条件中表现不同.请描述一下它是如何执行的?

var a=1;
function myFunc(){
    console.log(a);
    console.log(a)
}
myFunc();
//Output is:
1 
1

var a=1;
function myFunc(){
    console.log(a);
    var a=2;
    console.log(a)
}
myFunc();
//Output is:
undefined
2

var a=1;
function myFunc(){
    console.log(a);
    var a=2;
    console.log(a)
}
myFunc(a);
//Output is:
undefined
2
Run Code Online (Sandbox Code Playgroud)

为什么在第二种情况下它的打印未定义?在第三种情况下,我发送我的全局a作为参数,然后它的打印未定义.

Dan*_*nte 16

那是因为JavaScript将var声明移动到作用域的顶部,因此您的代码实际上是:

var a = 1;
function myFunc(){
    var a;            // a is redeclared, but no value is assigned
    console.log(a);   // therefore it evaluates to undefined
    a = 2;            // now a = 2
    console.log(a);   // and then it logs to 2
}
myFunc();
Run Code Online (Sandbox Code Playgroud)

此行为称为可变提升.

编辑 正如Beterraba所说,在第三个代码中它会记录,undefined因为在函数头中没有声明参数:

var a = 1;
function myFunc(a) {    // a is declared
    console.log(a);     // now a logs 1
    var a = 2;          // now a = 2
    console.log(a);
}
myFunc(a);
Run Code Online (Sandbox Code Playgroud)