闭包_定时器_BOM(进阶11)

2017-01-30  本文已影响0人  饥人谷_js_chen

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

Paste_Image.png
let fnArr = [];
for (let i = 0; i < 10; i ++) {
    let s = i;
    fnArr[i] =  ()=>s;  
}
console.log( fnArr[3]() );
var fnArr = [];
for (var i = 0; i < 10; i ++) {
    (function(){
        var s = i;
        fnArr[i] = function(){
            return s;
        }
    })();
}
console.log( fnArr[3]() );
var fnArr = [];
for (var i = 0; i < 10; i ++) {
    (function(n){
        fnArr[i] = function(){
            return n;
        }
    })(i);
}
console.log( fnArr[3]() );

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

var Car = (function () {
    var speed = 0;

    function setSpeed(s) {
        speed = s
    }
    //...todo
    function getSpeed() {
        return speed;
    }

    function accelerate(i = 10) {
        speed += i;
    }

    function decelerate(i = 10) {
        speed -= i;
    }

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

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

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

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

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

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

for(var i=0;i<5;i++){
    setTimeout(function(){
         console.log('delayer:' + i );
    }, 0);
    console.log(i);
}
//method 1:利用闭包实现
for(var i=0;i<5;i++){
    (()=>{
        var n = i;
        setTimeout(function(){
            console.log('delayer:' + n );
        }, 0)
    })();
    console.log(i);
}
//method 2:利用ES6新特性let的作用域
for(let i=0;i<5;i++) {
    let s = i;
    setTimeout(()=>console.log('delayer:' + s )  , 0);
    console.log(i);
}

题目6: 如何获取元素的真实宽高

let style = window.getComputedStyle(element);
console.log(style.height, style.width);//高、宽

题目7: URL 如何编码解码?为什么要编码?

题目8: 补全如下函数,判断用户的浏览器类型

//method 1
function isAndroid(){
  return   /android/i.test(navigator.userAgent);
}
funcnction isIphone(){
  return  /iphone/i.test(navigator.userAgent);
}
function isIpad(){
  return   /ipad/i.test(navigator.userAgent);
}
function isIOS(){
  return /iphone|ipad/i.test(navigator.userAgent);
}
//method 2
const isAndroid=()=>/android/i.test(navigator.userAgent);
const isIphone=()=>/iphone/i.test(navigator.userAgent);
const isIpad=()=>/ipad/i.test(navigator.userAgent);
const isIOS=()=>/iphone|ipad/i.test(navigator.userAgent);
上一篇下一篇

猜你喜欢

热点阅读