JS易错

发布于 2021-12-21  202 次阅读


1

var  a  = 25;
function abc () {
console.log(a);
var a = 10;
}

abc(); //undefined

原因:在函数执行的时候,会先将声明提前,变成

var  a  = 25;
function abc () {
var a ;
console.log(a);
a=10;
}

打印a的时候他并没有被赋值,所以为undefined

2

f1();
console.log(c);
console.log(b);
console.log(a);
function f1 () {
    var a = b = c = 9;
    console.log(a);
    console.log(b);
    console.log(c);
}
f1();
console.log(c); //9
console.log(b); //9
console.log(a);  //a未定义
function f1 () {
    var a = b = c = 9;
    console.log(a); //9
    console.log(b); //9
    console.log(c); //9
}

前提知识:

var a = b = c = 9; //这句话等价于一下三句:
	var a = 9;
	b = 9;
	c = 9;

那么说明:a为局部变量而b和c是全局变量,所以在全局作用域下c=9,b=9,而a未定义,在f1()中,a=b=c=9. 图解说明