题:改写如下代码
function test() { for (var i=0; i<3; i++) { setTimeout(function() { console.log(`time: ${new Date().getSeconds()}, index: ${i}`) }, 1000) } }
结果: time: x, index: 3 共打印3次 (x不定)
答:1
function test12() { for (var i=0; i<3; i++) { (function (i) { setTimeout(function() { console.log(`time: ${new Date().getSeconds()}, index: ${i}`) }, i*1000) })(i) } }
结果: time x, index: 0
time x, index: 1
time x, index: 2
答:2
function test() { for (let i=0; i<3; i++) { setTimeout(function() { console.log(`time: ${new Date().getSeconds()}, index: ${i}`) }, 1000) } }
改var为let
答:3
function test1() { for (var i=0; i<3; i++) { function a(i) { setTimeout(function() { console.log(`time: ${new Date().getSeconds()}, index: ${i}`) }, i*1000) } a(i) } }
用非匿名函数代替自执行函数