闭包基本上是内部函数可以访问其范围之外的变量,可用于实现隐私和创建函数工厂定义一个数组,循环遍历这个数组并在延迟3秒后打印每个元素的索引先看一个不正确的写法:const arr = [10, 12, 15, 21];for (var i = 0; i < arr.length; i++) { setTimeout(function() { alert(‘The index of this number is: ’ + i); console.log(‘The index of this number is: ’ + i); }, 3000);}看下执行效果:如上图:3秒后每次都是打印4,而不是0,1,2,3。原因:因为setTimeout函数创建的是一个可以访问其外部作用域的函数(闭包),该作用域包含索引i的循环。经过3秒后,i的值已经变为4。正确的写法:写法一:const arr = [10, 12, 15, 21];for (var i = 0; i < arr.length; i++) { setTimeout(function(i_local){ return function () { alert(‘The index of this number is: ’ + i_local); console.log(‘The index of this number is: ’ + i_local); } }(i), 3000)}写法二:const arr = [10, 12, 15, 21];for (let i = 0; i < arr.length; i++) { setTimeout(function() { alert(‘The index of this number is: ’ + i); console.log(‘The index of this number is: ’ + i); }, 3000);}