【问题标题】:variable cannot be reached inside foreach loop在 foreach 循环中无法访问变量
【发布时间】:2019-10-25 12:51:00
【问题描述】:

我正在尝试为对话流构建一个 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,但我不明白为什么?

【问题讨论】:

  • VS Code“未使用变量”的意思是,该值永远不会被读取。
  • 我的意思是变量永远不会被分配任何值。所以函数总是返回 undefined 。即使 console.log 打印“找到”。
  • 如果您将代码切换到for 循环,代码是否有效?由于forEach 循环创建了一个函数,因此作用域可能不同。此外,forEach 循环更慢。
  • 不,我尝试了 for 循环和every 而不是foreach。问题始终保持不变,在循环内它创建了一个新的匹配变量,但不使用已经声明的变量。

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


【解决方案1】:

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

1) 在顶部添加“use strict”。
2) 定义函数为

const findclass = () => {}

而不是 var

【讨论】:

    【解决方案2】:

    我的猜测是你的声明:

    var match ...
    

    正在吊装...见:

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

    在您声明的代码中:

    var match ...
    

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

    let match;
    

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

    【讨论】:

    • 已经试过了,没有运气。我认为云功能 webhook 强制某种“使用严格”(只是概率)
    【解决方案3】:

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

    另外,在 VSCode 中,如果您只是分配一个变量,而不是使用它(例如,在 return 语句中),它会将变量显示为未使用,因此这是意料之中的。

    【讨论】:

    • 我确信它匹配,因为控制台上打印了“found”。
    猜你喜欢
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    相关资源
    最近更新 更多