How does let in for loop work?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var messages = ["Check!","This!","Out!"]; for (var i = 0; i < messages.length; i++) { setTimeout(function () { console.log(messages[i]); }, i * 1500); } // -> prints 3* undefined for (let i = 0; i < messages.length; i++) { setTimeout(function () { console.log(messages[i]); }, i * 1500); } // -> prints out the array |
我了解"var"是如何工作的,我已经很习惯了它——范围是功能性的。然而,LET声明还不清楚。我知道是有块范围,但是为什么在这个例子中这很重要?在这个例子中,for循环在这两种情况下都需要很长的时间。为什么让列印出阵列?
let allows you to declare variables that are limited in scope to the
block, statement, or expression on which it is used. This is unlike
the var keyword, which defines a variable globally, or locally to an
entire function regardless of block scope.
在这里查看更多详细信息https://developer.mozilla.org/en/docs/web/javascript/reference/statements/let