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>