Created
May 19, 2018 06:26
-
-
Save kunyaoxu/ec58ab7b321ff2ddf8380066490915c1 to your computer and use it in GitHub Desktop.
This file contains 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
/*問題出在作用域(scope),原先的程式碼中i變數的作用域是在整個createArrayOfFunctions()函式中, | |
陣列中裡每個函式裡面的i在return的時候都會等於y的值,這樣一來就形成了bug, | |
我的解決方案是利用let宣告迴圈的i變數或是將函式改用閉包的方式來將變數的作用域改成我們所想要的範圍內即可*/ | |
function createArrayOfFunctions(y) { //let的改法 | |
var arr = []; | |
for(let i = 0; i<y; i++) { | |
arr[i] = function(x) { return x + i; } | |
} | |
return arr; | |
} | |
function createArrayOfFunctions_2(y) { //閉包 | |
var arr = []; | |
var newFunc = function(ii) { return function(x){return x + ii;};}; | |
for(var i = 0; i<y; i++) { | |
arr[i] = newFunc(i); | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment