js实现几种依次打印1的方法

题:改写如下代码

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)
    }
}

用非匿名函数代替自执行函数

 

posted @ 2019-09-11 21:44  jiaqiq  阅读(649)  评论(0编辑  收藏  举报