javascript - 带参数调用回调

标签 javascript parameters callback

我正在尝试运行一个在循环调用之间等待 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/

相关文章:

javascript - 在javascript中将回调函数设置为新窗口

javascript - 使用 jquery scrollify 更改固定 div 的 Div 内容

javascript - Facebook JavaScript

c# - C# 是否支持可变数量的参数,如何支持?

c# - 无法在 C# 中将子接口(interface)作为参数传递

c++ - 以优雅礼貌的方式在 C++ 中处理 GTK 回调

node.js - 如何在 NodeJS 中异步调用 MySQL 数据库

javascript - 上下滚动不起作用

javascript - 在 Javascript 中检查文本框是否为空

javascript - 我可以使字母过滤函数中的语句满足两个参数,同时保留语句本身的名称吗?