JS递归,预编译

2020-03-14  本文已影响0人  iliuqiang

变量提升经典题目:
第一题:

global=100;
function test(){
    console.log(global); // undefined
    global=200;
    console.log(global); // 200
    var global=300;
}
test();
var global;

利用预编译的Global Object和Activation Object思想来分析:

GO={
    global:100;
    test:xxx
}

AO={
    global:undefined
}

test中第一步打印时,发现AO中有自己的global属性,就不去找GO中的global属性了,因此打印出undefined,而不是100。

AO={
    global:200
}

因此第二步打印时,打印出200
第二题:

function test(){
    console.log(b); //undefined
    if(a){
        var b=100;
    }
    console.log(b); //undefined
    c=234;
    console.log(c); //234
}
var a;
test();
a=10;
console.log(c); //234

利用预编译的Global Object和Activation Object思想来分析:

GO={
    a:undefined;
    test:xxx
}

AO={
    b:undefined
}

注意:预编译是发生在函数执行之前,因此这里不管if条件成立不成立,都会存在变量b的声明。
因此第一步打印b时,值为undefined。
继续往下走,由于此时AO中没有a变量,因此去GO中找,发现值为undefined,所以if条件不成立,b也就未能赋值成功,因此下一步打印b时,值仍为undefined。

第3题:

a=100;
function demo(e){
    function e(){};
    arguments[0]=2;
    console.log(e);  //2
    if(a){
        var b=123;
        function c(){}
    }
    var c;
    a=10;
    var a;
    console.log(b); //undefined
    f=123;
    console.log(c); //undefined
    console.log(a); //10
}
var a;
demo(1);
console.log(a); //100
console.log(f); //123

利用预编译的Global Object和Activation Object思想来分析:

GO={
    a:100;
    demo:xxx
}

AO={
    e:undefined,
    b:undefined,
    c:undefined,
    a:undefined
}

接下来参数的第一个被赋值为了2,因此:

AO={
    e:2,
}

因此此时打印e的值为2。
下面进入if条件,由于在AO中a的值为undefined,所以条件不成立,又由于新规定if条件语句中,不能定义函数,所以c的值为undefined。因此此时:

AO={
    e:2,
    b:undefined,
    c:undefined,
    a:undefined
}

接下来a被赋值为10,所以:

AO={
    e:2,
    b:undefined,
    c:undefined,
    a:10
}

所以此时b,c,a的打印值分别为:undefined,undefined,10
接下来在全局作用域中打印a,由于在GO对象中存在a,

GO={
    a:100,
}

因此此时打印a的值为100。
由于f在AO中未声明,因此放入GO中:

GO={
    a:100;
    demo:xxx,
    f:123
}

所以此时打印f的值为:123

隐式类型转换题目:
第1题:

if(typeof(a)&&-true+(+undefined)+''){
    console.log('a');
}else{
    console.log('b');
}

答案:a
分析:

typeof(a)   => 'undefined';
-true       => -1
+undefined  => NaN
-1+NaN      => NaN
NaN+''      => 'NaN'

因此,'undefined'&&'NaN'条件成立,所以打印出a。

第2题:

if(10+'10'*2==30){
    console.log('a');
}else{
    console.log('b');
}

答案:a
分析:

'10'*2     => 20
10+20==30  => true

因此答案为a。

第3题:

if(!!" "+!!""-!!false){
    console.log('a');
}else{
    console.log('b');
}

答案:a
分析:

!!" "             => true
!!""              => false
!!false           => false
true+false-false  =>1

所以条件成立,打印出a

上一篇 下一篇

猜你喜欢

热点阅读