Javascript

时间:2017-06-05 21:16:40

标签: javascript

var messages = [
    "Hello, how are you??",
    "I'm good, thank you",
    "Yeah, it's been a long since we last spoke"
];

function test() {
    console.log(`it is inside the test function ${i}`);
}

for (var i = 0; i < messages.length; i++ ) {
    setTimeout(function() {
        console.log(`i am inside ${i}`);
    }, i * 2000);

    test();

}

以上代码的输出是:

it is inside the test function 0 it is inside the test function 1 it is inside the test function 2 is it outside 3 i am inside 3

对于上面的代码,为什么i函数中setTimeout的值在第一个循环中设置为3而不是test函数??? / p>

0 个答案:

没有答案