因此,努力學習一些關於ES6,我就過來了這個鏈接,http://es6-features.org/#BlockScopedVariables這個循環如何在Es5/Es6上工作?
// ES6
let callbacks = []
for (let i = 0; i <= 2; i++) {
callbacks[i] = function() { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4
// ES5
var callbacks = [];
for (var i = 0; i <= 2; i++) {
(function (i) {
callbacks[i] = function() { return i * 2; };
})(i);
}
callbacks[0]() === 0;
callbacks[1]() === 2;
callbacks[2]() === 4;
我想知道爲什麼在ES5方法中,我們使用的是直接的函數返回I * 2的值?
但是在ES6中,只分配循環中的值有效?
基本上,
- 想知道爲什麼這種差異會出現?
- 該循環如何執行?
- 我發現區別是由於「塊範圍(讓)&全局範圍(var)」,但想知道更多關於執行/運行點?
- 所以我們不想使用即時函數來保存ES6中變量的當前狀態?
的[JavaScript中的潛在的重複 - 「讓」 的關鍵字與「變種「關鍵字」(http://stackoverflow.com/questions/762011/javascript-let-keyword-vs-var-keyword) –
@ TaoP.R。如果重複,請解釋該循環如何工作? – Sathish
另請參閱[let'和block作用域循環的說明](http://stackoverflow.com/a/30900289/1048572)(不確定是否重複) – Bergi