在foreach循环中无法访问变量

时间:2019-10-24 17:42:12

标签: javascript node.js google-api-nodejs-client dialogflow-fulfillment

我正在尝试为对话流程构建一个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`
    });
  }

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

3 个答案:

答案 0 :(得分:0)

我的猜测是您的声明:

var match ...

正在吊起...请参阅:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

在您的代码中,您已经声明:

var match ...

两次。我认为findClass函数主体中的声明可能希望更改为局部变量...

let match;

(这是猜测,将根据要求删除此答案,或者如果出现更好的答案,则将其删除。)

答案 1 :(得分:0)

我的猜测是,循环中实际上没有任何匹配项,因此match仍未定义。您确定循环中确实有匹配项吗?

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

答案 2 :(得分:0)

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

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

const findclass = () => {}

代替var