loops - In Pug, how to use a variable outside (set for global use) the each loop it is created in?
问题描述
Below, I'm trying to get the personRef variable inside (locally set scope) the pug each loop of person in persons to come out. That way on the following line PersObj which I need for each object loop it's a part of can use the personRef variable from the loop right above. Basically, I need the local scope in the loop to be set globally outside the loop.
each object in objects
- var objNum = objects.indexOf(vehicle)+1
- var personRef=person.object_ref
each person in persons
- var personNum = persons.indexOf(driver)+1
if (some condition) && (object.person_ref == objNum)
- var personRef=object.person_ref
- break
else if (condition)
- var personRef= personNum
else if (condition)
- continue
PersObj(id = "O"+objNum, PersonRef = "P"+personRef)
解决方案
很难理解您想要实现的确切行为,但我会尝试。“-var personRef = something”定义了一个变量。您只需要在代码中使用一次。如果你在循环之外定义它,你也可以在里面使用它。如果你在循环中再次有“- var personRef = something”,你用一个只能在循环范围内使用的变量“覆盖”它。你总是可以像这样重新分配一个变量值:“personRef = somethingElse”而不使用“-var”。
所以它应该看起来像这样:
each object in objects
- var objNum = objects.indexOf(vehicle)+1
- var personRef=person.object_ref // define the variable here
each person in persons
- var personNum = persons.indexOf(driver)+1
if (some condition) && (object.person_ref == objNum)
- personRef=object.person_ref // here you dont need var, because you only reassign a value
- break
else if (condition)
- personRef= personNum // here as well
else if (condition)
- continue
PersObj(id = "O"+objNum, PersonRef = "P"+personRef)
除此之外,我真的无法说出代码应该做什么,请您详细说明该代码应该做什么。还请解释一下:什么是“物体” 什么是“人” 什么是“车辆” 什么是“司机”
推荐阅读
- arrays - 为什么 Ruby 的 Array#count 对于大型数组不可靠?
- java - 使用预填充信息创建表时出现 SQLITE 数据库错误(表有 3 列,但提供了 2 个值)
- oauth - 如何缓解客户端放弃刷新令牌请求而不是服务器放弃的 OAuth 问题?
- ansible - ansible,带有循环的 jinja 模板,丢失换行符
- r - 重新创建文件扩展名以便在 R 中轻松加载
- node.js - 通过 Dialogflow 实现在 Google Actions 上设置上下文
- java - 在程序处于活动状态时更改 Medusa Gauge 的 maxValue
- javascript - 无法使用前导零 ListJS 对小数进行排序
- javascript - 使用 d3.js 的 svg 视图框:图形上方的空间仍然太大
- javascript - 导入远程主机上的所有模块时的包裹构建问题