首页 > 解决方案 > 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)

标签: loopsvariablesscopepugeach

解决方案


很难理解您想要实现的确切行为,但我会尝试。“-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)

除此之外,我真的无法说出代码应该做什么,请您详细说明该代码应该做什么。还请解释一下:什么是“物体” 什么是“人” 什么是“车辆” 什么是“司机”


推荐阅读