# 涓€閬揓avascript闈㈣瘯棰樺紩鍙戠殑琛€妗?绮鹃€夊墠绔紑鍙慗AVASCRIPT

www.MyException.Cn  网友分享于：2013-10-08  浏览：0次

## Question 1

for (var i = 0; i <5 ; i++) {
setTimeout(function(){
console.log(i)
),1000}
}
console.log(i)
• Q锛氳繖閬撻鐩細杈撳嚭浠€涔堬紵
• A锛氳繖閬撻鐩繕姣旇緝绠€鍗曪紝濡傛灉瀵笿avascript绋嶅井鏈変竴鐐规繁鍏ョ殑鍚屽閮戒細鍙戠幇杩欓亾棰樼洰寰幆閲岄潰鍑虹幇浜嗛棴鍖?/strong>锛屽洜姝よ緭鍑虹殑鏁板瓧鏄畬鍏ㄧ浉鍚岀殑锛屾渶鍚庣殑杈撳嚭涔熸槸瀹屽叏鐩稿悓鐨勩€?/li>
• 鑰冪偣锛氶棴鍖咃紝锛堜吉锛夊紓姝?/li>

## Question 2

for (let i = 0; i <5 ; i++) { //娉ㄦ剰var鍙樻垚浜唋et
setTimeout(function(){
console.log(i)
},1000)
}
console.log(i)
• Q锛氳繖閬撻鐩細杈撳嚭浠€涔堬紵
• A锛氳繖閬撻鐩叾瀹炴槸涓潙銆傞鍏堥鐩笌Q1鐨勫尯鍒氨鏄彉閲廼鐨勫畾涔夋敼涓轰簡鍏抽敭瀛條et锛屼娇鐢╨et鐨勬椂鍊欎細灏嗗彉閲忛檺鍒跺湪寰幆涔嬩腑锛屽洜姝ょ浜屼釜杈撳嚭鍏跺疄浼氭姤閿欍€傚彟澶杝etTimeout瀹炵幇浜嗭紙浼級寮傛锛屽悓鏃跺洜涓簂et灏嗗彉閲忎綔鐢ㄥ煙杩涜浜嗘帶鍒讹紝鐮村潖浜嗛棴鍖呯粨鏋勶紝鍥犳浼氭寜鐓ф甯搁『搴忚緭鍑恒€?/p>

鍏充簬let鍏抽敭瀛梉^3]

Use the let statement to declare a variable, the scope of which is聽restricted to the block in which it is declared. You can assign values to the variables when you declare them or later in your script.
A variable聽declared using let cannot be used before its declaration or an error will result..

• 鑰冪偣锛氶棴鍖咃紝锛堜吉锛夊紓姝ワ紝浣滅敤鍩?/p>

## Question 3

for (var i = 0; i <5 ; i++) {  //DO NOT MODIFY
setTimeout(function(){ //DO NOT MODIFY
console.log(i)
},1000)
}
console.log(i)  //DO NOT MODIFY
• Q锛氫慨鏀逛笂杩颁唬鐮侊紙閮ㄥ垎琛屼笉鍏佽淇敼锛屽彲浠ュ湪浠ｇ爜闂存彃鍏ワ級锛屼互瀹炵幇鈥滄瘡闅斾竴绉掕緭鍑轰竴涓暟瀛楀苟涓旈『搴忎负0-5鈥?/li>
• A

1. 棣栧厛鑰冨埌浜嗙牬鍧忛棴鍖呯粨鏋勶紝鐮村潖闂寘鐨勬柟娉曞緢澶氾紝鏈€绠€鍗曠殑鏄皢璺ㄥ煙鍙橀噺杞崲鎴愯寖鍥村唴鐨勫彉閲?/strong>
2. 鍏舵鑰冨埌浜唖etTimeout浜嬩欢闃熷垪鐨勫鐞?/p>

for (var i = 0; i <5 ; i++) {
(function(i){
setTimeout(function(){
console.log(i)
},1000*i)
})(i)           //灏唅浣滀负鍙傛暟浼犲叆鍖垮悕鍑芥暟锛屽姝ょ牬鍧忎簡闂寘鍐呰法鍩熻闂?/span>
}
setTimeout(function (){
console.log(i);
}, 5000);               //寮鸿灏?鏀惧埌5sec鍚庤緭鍑?/span>

• 鑰冪偣锛氶棴鍖咃紝锛堜吉锛夊紓姝ワ紝浣滅敤鍩燂紝浜嬩欢闃熷垪

## Question 4

window.setTimeout(function (){
console.log(2)
},1);

//Ouput for a long time
for (var i = 0; i < 1000; i++) {
console.log('');
};

console.log(1)

window.setTimeout(function (){
console.log(3)
},0);
• Q锛氳繖閬撻鐩細杈撳嚭浠€涔堬紵
• A锛氬彲鑳芥湁浜涘悓瀛︿細璁板緱锛宻etTimeout鏄竴涓洖璋冨嚱鏁帮紝鍥犳鏃犺寤舵椂澶氬皯缁撴灉閮芥槸鏈€鍚庤緭鍑恒€?/li>
• 鑰冪偣锛氾紙浼級寮傛锛屼簨浠堕槦鍒?/li>

## Question 5

setTimeout(function(){console.log(4)},0);
new Promise(function(resolve){
console.log(1)

//time consuming ops
for( var i=0 ; i<10000 ; i++ ){
i==9999 && resolve();
}

console.log(2)
}).then(function(){
console.log(5)
});
console.log(3);
• Q锛氳繖閬撻鐩細杈撳嚭浠€涔堬紵
• A锛氳緭鍑烘槸12354

鍏充簬杩欎釜杈撳嚭锛屾湁濡備笅鍑犱釜閫昏緫锛?/p>

2. 杈撳嚭1
4. 杈撳嚭2
5. 杈撳嚭3
11. 鎵ц瀹屾瘯

### 涓よ€呯殑鍏蜂綋瀹炵幇

• macrotasks: setTimeout setInterval setImmediate I/O UI娓叉煋
• microtasks: Promise process.nextTick Object.observe MutationObserver

### 浠庤鑼冧腑鐞嗚В

2. 濡傛灉 task A 涓簄ull (閭ｄ换鍔￠槦鍒楀氨鏄┖)锛岀洿鎺ヨ烦鍒扮6姝?/li>
6. 鍦?microtask 涓€夊嚭鏈€鏃╃殑浠诲姟 , 璺冲埌 b
7. 璺冲埌绗竴姝?/li>