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++) {
~function (j) {
fnArr[j] = function () {
return j;
};
}(i)
}
console.log(fnArr[3]());
var fnArr = [];
for (var i = 0; i < 10; i++) {
output(i)
}
function output(j) {
fnArr[j] = function () {
return j;
};
}
console.log(fnArr[3]());
2. 封裝一個汽車對象烘挫,可以通過如下方式獲取汽車狀態(tài)
var Car = (function () {
var speed = 0;
function setSpeed(s) {
speed = s;
}
function getSpeed() {
console.log(speed)
return speed;
}
function accelerate() {
speed += 10;
}
function decelerate() {
speed -= 10;
}
function getStatus() {
if (speed > 0) {
console.log('running');
return "runnings";
} else if (speed === 0) {
console.log('stop');
return "stop"
}
}
return {
setSpeed: setSpeed,
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. 下面這段代碼輸出結(jié)果是? 為什么?
var a = 1;
setTimeout(function(){
a = 2;
console.log(a);
}, 0);
var a ;
console.log(a);
a = 3;
console.log(a);//輸出1 3 2 饮六;由于js是單線程操作卤橄,定時器必須等到本次執(zhí)行的所有代碼都執(zhí)行完,才會執(zhí)行虽风。
4. 下面這段代碼輸出結(jié)果是? 為什么?
var flag = true;
setTimeout(function(){
flag = false;
},0)//需要等到其他代碼執(zhí)行完才可以執(zhí)行,
while(flag){}//flag一直是true辜膝,所以無限循環(huán)執(zhí)行下去
console.log(flag);//不會執(zhí)行
var a = document.querySelectorAll('.text')[0];//獲得元素
console.log(window.getComputedStyle(a).height);//獲取元素真實(shí)高度
console.log(window.getComputedStyle(a).width);//獲取元素真實(shí)寬度
function isAndroid(){
/Android/ig.test(window.navigator.userAgent)
}
function isIphone(){
/Iphone/ig.test(window.navigator.userAgent)
}
function isIpad(){
/Ipad/ig.test(window.navigator.userAgent)
}
function isIOS(){
/Ipad | Iphone | Iwatch/ig.test(window.navigator.userAgent)
}