Javascript 无法在foreach循环内访问变量

Javascript 无法在foreach循环内访问变量,javascript,node.js,google-api-nodejs-client,dialogflow-es-fulfillment,Javascript,Node.js,Google Api Nodejs Client,Dialogflow Es Fulfillment,我试图为对话流构建一个webhook,但无法访问代码中的某些变量 当我运行代码时 比赛结果是没有定义的 var findclass = (data, day, time) => { var match; data.forEach(entry => { if (entry.day === day && entry.time === time) { console.log("found");

我试图为对话流构建一个webhook,但无法访问代码中的某些变量 当我运行代码时 比赛结果是没有定义的

var findclass = (data, day, time) => {
      var match;
      data.forEach(entry => {
        if (entry.day === day && entry.time === time) {
          console.log("found");
          match=entry;//this statement has no effect on above var match
//instead it creates a new local variable
        }
      });
      return match;
    }



exports.tt = functions.https.onRequest((request, response) => {
  let qr = request.body.queryResult;
  let day = qr.parameters.day;
  let time = parseInt(qr.parameters.time.substring(11, 13));
  let data = [
    {
      day: "monday",
      time: 11,
      type: "lecture",
      batches: ["A", "B1", "B4", "B3", "B2"],
      subject: {
        name: "Basic Numerical Methods",
        name_short: "BNM",
        coursecode: "17B1NMA531",
        coursecode_short: "17MA531"
      },
      class: "CS1",
      teachers: "SSH",
      semester: 5
    },
    {
      day: "monday",
      time: 15,
      type: "lecture",
      batches: ["A6", "A9"],
      subject: {
        name: "Environmental Science",
        name_short: "EVS",
        coursecode: "15B11GE301",
        coursecode_short: "GE301"
      },
      class: "CS1",
      teachers: "EKT",
      semester: 5
    }]
var match = findclass(data, day, time);
  console.log(JSON.stringify(match));
  if (match) {
    response.send({
      fulfillmentText: `Yes, ${match.subject.name_short || match.subject.name}`
    });
  } else {
    response.send({
      fulfillmentText: `No class on ${day} ,${time} hr`
    });
  }

另外,如果我删除return match语句,vscode代码显示var match未使用,这意味着它没有考虑match=entry,但我不明白为什么?

我猜您的声明是:

var match ...
正在吊装。。。见:

您在代码中声明:

var match ...
两次。我认为findClass函数体中的声明可能需要更改为局部变量

let match;

(这是一个猜测,将根据请求删除此答案,或者如果有更好的答案出现)。

我的猜测是,循环中实际上没有匹配的内容,因此
match
仍然未定义。你确定循环中有匹配的东西吗


另外,在VSCode中,如果您只是分配一个变量,而没有使用它(例如,在
return
语句中),它将显示未使用的变量,因此这是预期的。

我不知道原因,但有两个更改修复了代码

1) 在顶部添加“严格使用”。
2) 将函数定义为

const findclass = () => {}

VS代码“unused variable”的意思是永远不会读取该值,而不是var

。所以函数总是返回未定义的。即使console.log打印“found”。如果您将其切换为
for
循环,代码是否有效?由于
forEach
循环创建函数,因此作用域可能不同。另外,
forEach
循环速度较慢。不,我尝试了for循环,也尝试了every而不是forEach。问题始终是一样的,在循环中它创建了一个新的匹配变量,但没有使用已经声明的变量。我确信它匹配,因为控制台上打印了“found”。已经尝试过了,但没有成功。我认为云函数webhook强制某种“严格使用”(只是一种可能性)