进阶任务11-闭包、定时器、BOM

2017-07-28  本文已影响0人  RookieD
    var fnArr = [];
    for (var i = 0; i < 10; i ++) {
        fnArr[i] =  function(){
            return i;
        };
    }
    console.log( fnArr[3]() ); 

以上代码输出为10

修改后代码一:

    var fnArr = [];
    for (var i = 0; i < 10; i ++) {
        fnArr[i] =  function(i){
            return function() {
                return i;
            }
        }(i);
    }

修改后代码二:

    var fnArr = [];

    for (var i = 0; i < 10; i ++) {
        fnArr[i] =  function(){
             var j = i;
            return function() {
                return j;
            }
        }(i);
    }
var Car = (function(){
   var speed = 0;
   function setSpeed(s){
       speed = s
   }
   function getSpeed(){
       console.log(speed)
   }
   function accelerate(){
       speed += 10;
   }
   function decelerate(){
       speed -= 10;
   }
   function getStatus(){
       if(speed > 0) {
           console.log("running")
       }else {
           console.log("stop")
       }
   }
   return {
      setSpeed: setSpeed,
      getSpeed: getSpeed,
      accelerate: accelerate,
      decelerate: decelerate,
      getStatus: getStatus,
   }
})()
var a = 1;
setTimeout(function(){
    a = 2;
    console.log(a);
}, 0);
var a ;
console.log(a);
a = 3;
console.log(a);

输出结果为1、3、2,首先a被赋值为1,虽然setTimeout设置为0秒后执行,但是它会等待其他代码执行完毕后再计时并执行,接着声明a没有变化,然后打印1,接着a被赋值为3,然后打印3,最后执行setTimeout内的代码,a被赋值为2,打印2

var flag = true;
setTimeout(function(){
    flag = false;
},0)
while(flag){}
console.log(flag);

一直执行while部分的代码段陷入死循环,因为setTimeout并不会在while代码段之前执行,所以flag的值为true,while代码段陷入死循环

题目5: 下面这段代码输出?如何输出delayer: 0, delayer:1...(使用闭包来实现)
for(var i=0;i<5;i++){
    setTimeout(function(){
         console.log('delayer:' + i );
    }, 0);
    console.log(i);
}

以上代码输出结果:0 1 2 3 4 5次delayer:5

代码修改:

for(var i=0;i<5;i++){
    setTimeout(function(i){
        return function() {
            console.log('delayer:' + i );
        }
    }(i), 0);
    console.log(i);
}
let style = window.getComputedStyle(element);
console.log(style.width, style.height);  
function isAndroid(){
    return /Android/.test(navigator.userAgent);
}
function isIphone(){
    return /iPhone/.test(navigator.userAgent)
}
function isIpad(){
    return /iPad/.test(navigator.userAgent);
}
function isIOS(){
    return /(iPad)|(iPhone)/i.test(navigator.userAgent);
}
上一篇下一篇

猜你喜欢

热点阅读