在JavaScript中让vs var [英] let vs var in javascript
本文介绍了在JavaScript中让vs var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我了解到let具有块作用域,而var具有功能作用域。但是在这种情况下,我不明白如何使用let解决问题
I understand that let has block scope and var has functional scope. But I do not understand in this case, how using let will solve the problem
const arr = [1,2,3,4];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(arr[i])
}, 1000);
} // Prints undefined 5 times
const arr = [1,2,3,4];
for (let i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(arr[i])
}, 1000);
} // Prints all the values correctly
推荐答案
首先,输出将是四倍而不是五倍(如您的注释中所述)。
我将您的代码粘贴到Babel REPL中,这就是我得到的,
First of all, the output will be four times and not five times(as mentioned in your comment). I pasted your code in Babel REPL and this is what I got,
"use strict";
var arr = [1, 2, 3, 4];
var _loop = function _loop(i) {
setTimeout(function () {
console.log(arr[i]);
}, 1000);
};
for (var i = 0; i < arr.length; i++) {
_loop(i);
}
您是否知道let在内部如何工作? :-)
Do you see how let works internally now? :-)
这篇关于在JavaScript中让vs var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文