题目1: 下面的代码输出多少?修改代码让fnArri 输出 i。使用两种以上的方法
- 输出:10
- method 1:利用ES6的let变量(const常量)的作用域
let fnArr = [];
for (let i = 0; i < 10; i ++) {
let s = i;
fnArr[i] = ()=>s;
}
console.log( fnArr[3]() );
- method 2:利用var的函数作用域和立即执行函数
var fnArr = [];
for (var i = 0; i < 10; i ++) {
(function(){
var s = i;
fnArr[i] = function(){
return s;
}
})();
}
console.log( fnArr[3]() );
- method 3:与method2 类似,区别是给立即函数传入参数
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);
- 输出:1 3 2
- 因为setTimeout会在当前代码执行队列结束后执行(即异步延迟到同步代码执行结束后才允许执行)
题目4: 下面这段代码输出结果是? 为什么?
var flag = true;
setTimeout(function(){
flag = false;
},0)
while(flag){}
console.log(flag);
- 没有任何输出
- 因为setTimeout会在当前代码执行队列结束后执行,while循环结束后才会执行setTimeout中的方法,故while循环的条件永远是true,会无限循环下去
题目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,delayer5,delayer5,delayer5,delayer5,delayer5(不包括','但以','间隔)
//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);