Created
March 12, 2019 16:22
-
-
Save gotraveltoworld/8cd972ca2cf90d51d3b754f1854139d9 to your computer and use it in GitHub Desktop.
To practice the JS setTimeout: 測試迴圈內 "i" 的結果,這題要研究var 和 let 之間的關係(重點在全域綁定和區域綁定), let vs var
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 測試迴圈內 "i" 的結果,這題要重新研究var 和 let 之間的關係(重點在全域綁定和區域綁定) | |
for (var i = 0; i < 10; i ++) { | |
setTimeout(function() { | |
console.log(i); | |
}, 10); | |
} | |
for (let i = 0; i < 10; i ++) { | |
setTimeout(function() { | |
console.log(i); | |
}, 10); | |
} | |
// ES5 要正確的寫法:(利用function scope) | |
// for (var i = 0; i < 10; i++) { | |
// (function (j) { | |
// setTimeout(function () { | |
// console.log('這執行第' + j + '次'); | |
// }, 10); | |
// })(i); | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment