美文网首页
JS基础编码题分析(1)

JS基础编码题分析(1)

作者: 雨中晨星 | 来源:发表于2019-12-10 12:19 被阅读0次
    var hellword=(function(){
            console.log('hello one');
            setTimeout(function(){
                console.log('hello two');
            },100);
            setTimeout(function(){
                console.log('hello three');
            },0);
            console.log('hello four');
        }());
    

    依次输出:hello one,hello four,hello three,hello two
    分析过程:先打印hello one,再跳过定时器打印hello four,然后两个定时器先打印定时器时间短的hello three,最后打印定时器时间长的hello two。

    var a = {
            id:10
        }
        b=a;
        b.id=1;
        b.name='test';
        console.log(a);
    

    输出 {id:1,name:"test"}
    分析过程:对象是一个引用数据类型,简单的b=a只是把a在内存中的地址赋值给了b,所以修改b会影响a。

    var length=10;
        function fn(){
            console.log(this.length);
        }
        var obj = {
            length:5,
            method:function(fn){
                fn();
                arguments[0]();
            }
        }
        obj.method(fn,1);
    

    输出10,2
    分析过程:fn(),此时this指向window,所以this.length=10;arguments0中的this永远指向arguments,而arguments本身有一个length属性,就是参数的个数,所以打印出2。

    (function test() {
            var a=b=5;
            alert(typeof a);
            alert(typeof b);
        })()
        alert(typeof a);
        alert(typeof b);
    

    依次弹出number,number,undefined,number
    分析过程:自调用函数会开辟一个局部作用域,var a=b=5这句代码var只会修饰a,所以a是一个局部变量,b是全局变量,所以第三次弹出为underfined。

    [1,2,3].map(parseInt);
    

    输出结果:[1,NaN,NaN];
    分析过程:parseInt() 函数可解析一个字符串,并返回一个整数。语法:parseInt(string, radix)
    string,必需。要被解析的字符串。
    radix,表示要解析的数字的基数。该值介于 2 ~ 36 之间。如果省略该参数或其值为 0,则数字将以 10 为基础来解析。如果它以 “0x” 或 “0X” 开头,将以16为基数。如果该参数小于 2 或者大于 36,则 parseInt() 将返回 NaN。
    所以依次输出parseInt(1,0),parseInt(2,1),parseInt(3,2),也就是1,NaN,NaN。

    console.log(square(5));
    var square=function(n){
        return n*n;
    }
    

    执行结果:报错Uncaught TypeError: square is not a function
    分析过程:函数表达式方式声明的函数只能提升声明,但是不能提升赋值,所以不能在声明之前调用。

    console.log(2.0=='2'==new Boolean(true)=='1');
    

    执行结果:true
    分析过程:2.0==2返回true,true==new Boolean(true)返回true,true=='1'返回true,所以最终结果是true。

    for(var i=1;i<=5;i++){
        setTimeout(function() {
            console.log(i);
        },1000);
    }
    

    执行结果:6,6,6,6,6
    如何改造代码,使其输出1,2,3,4,5

    for(var i=1;i<=5;i++){
        (function (i){
            setTimeout(function () {
        console.log(i);
            }, 1000*i)
              })(i)
        }
    
    var a=10;
    function Foo(){
          if(true){
                let a = 4;
          }
          alert(a);
          }
    Foo();
    

    执行结果:弹出10
    分析过程:let声明的变量有块级作用域,所以let声明的a只是if花括号中生效,所以会向上级作用域查找。

    相关文章

      网友评论

          本文标题:JS基础编码题分析(1)

          本文链接:https://www.haomeiwen.com/subject/mzzwgctx.html