闭包-定时器-BOM

1.下面的代码输出多少?修改代码让 fnArri 输出 i。使用 两种以上的方法

   var fnArr = [];
    for (var i = 0; i < 10; i ++) {
        fnArr[i] =  function(){
            return i;
        };
    }
    console.log( fnArr[3]() );  // 10

方法1

   var fnArr = [];
    for (var i = 0; i < 10; i ++) {
      !function(i){
        fnArr[i] =  function(){
          return i;
        }
      }(i)
    }
    console.log( fnArr[3]() );    // 3

方法2

    var fnArr = [];
    for (var i = 0; i < 10; i ++) {
      fnArr[i] =  function(i){
        return function(){
          return i
              }
      }(i)
          }
    console.log( fnArr[3]() );   // 3

2.封装一个汽车对象,可以通过如下方式获取汽车状态

var Car = (function(){
   var speed = 0;
   function setSpeed(s){
       speed = s
   }
   ...
   return {
      setSpeed: setSpeed,
      ...
   }
})()
Car.setSpeed(30);
Car.getSpeed();   
Car.accelerate();
Car.getSpeed(); //40;
Car.decelerate();
Car.decelerate();
Car.getSpeed(); //20
Car.getStatus(); // 'running';
Car.decelerate(); 
Car.decelerate();
Car.getStatus();  //'stop';
var Car = (function(){
   var speed = 0;
   function setSpeed(s){
       speed = s
   }
   function getSpeed() {
     return speed
   }
   function accelerate() {
     speed += 10
   }
   function decelerate() {
      speed -= 10
   }
   function getStatus() {
     if (speed > 0) {
       return 'running'
     } else {
       return 'stop'
     }
   }
   return {
      setSpeed: setSpeed,
      getSpeed: getSpeed,
      accelerate: accelerate,
      decelerate: decelerate,
      getStatus: getStatus,
      speed: 'error'
   }
})()

3.下面这段代码输出结果是? 为什么?

var a = 1;
setTimeout(function(){
    a = 2;
    console.log(a);
}, 0);
var a ;
console.log(a);
a = 3;
console.log(a);

输出结果为1、3、2,原因见下

    var a;
    a = 1;
    var fun = function(){
        a = 2;
        console.log(a);   
    }
    setTimeout( fun, 0);   //2 (定时器排在了执行队列的最后,最后执行)
    var a ;
    console.log(a);    // 1
    a = 3;
    console.log(a);  //3

4.下面这段代码输出结果是? 为什么?

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

没结果,while语句中条件为true,该循环一直执行,setTimeout等待中,未执行,console.log等待中,未执行

5.下面这段代码输出?如何输出delayer: 0, delayer:1...(使用闭包来实现)

for(var i=0;i<5;i++){
    setTimeout(function(){
         console.log('delayer:' + i );
    }, 0);
    console.log(i);
}

变量提升

 var i
 var fun = function(){
         console.log('delayer:' + i );
  }
for(i=0;i<5;i++){
  setTimeout(fun , 0);  //delayer:5
  console.log(i);   // 0,1,2,3,4
}

输出结果依次为0,1,2,3,4,delayer:5,delayer:5,delayer:5,delayer:5,delayer:5
解决方法:利用立即执行函数,创建新作用域,传参

    for(var i=0;i<5;i++){
      !function(j){
        setTimeout(function(){
             console.log('delayer:' + j );
      } , 0);
        console.log(j);
      }(i)
    }

6. 如何获取元素的真实宽高

function  getStyle (element,key) {
 return  element.currentStyle ?
            element.currentStyle[key] : window.getComputedStyle(element, null)[key]
}
//获得