我正在尝试运行一个在循环调用之间等待 1 秒的脚本。但代码无法识别 i 参数。
for (var i = 0; i < lines.length; i++) {
var scanProgressInterval = setInterval(function(i) {
// Process the line, noting it might be incomplete.
if (lines[i].indexOf("(y/n)") > -1) {
console.log("includes (y/n)");
ws.emit('scan', JSON.stringify({scan: false, question: lines[i]}));
}
else if (lines[i].indexOf("any key") > -1) {
console.log("any key");
ws.emit('scan', JSON.stringify({scan: false, key: lines[i]}));
}
}, 1000);
}
这段代码有什么问题?
最佳答案
这里'i'是全局声明的。
尝试使用您的函数作为闭包。
function scanProgressInterval(i){
setInterval(function() {
// Process the line, noting it might be incomplete.
if (lines[i].indexOf("(y/n)") > -1) {
console.log("includes (y/n)");
ws.emit('scan', JSON.stringify({scan: false, question: lines[i]}));
}
else if (lines[i].indexOf("any key") > -1) {
console.log("any key");
ws.emit('scan', JSON.stringify({scan: false, key: lines[i]}));
}
}, 1000);
}
for (var i = 0; i < lines.length; i++) {
scanProgressInterval(i);
}
关于javascript - 带参数调用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104528/