【发布时间】: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