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

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

猜你喜欢

转载自www.cnblogs.com/jiaqi1719/p/11509022.html