简体   繁体   English

如何打破EJS模板语言的循环?

[英]How to break a loop with the EJS template language?

I am developping a simple web application with sails.js. 我正在使用sails.js开发一个简单的Web应用程序。

In my frontend code, i'm looping over an array of objects sent by the controller, and i am searching for a specific object. 在我的前端代码中,我遍历了由控制器发送的对象数组,并且正在搜索特定的对象。 I'd like to break the loop once the object has been found. 一旦找到对象,我想打破循环。 Is there a clean way to do that using the ejs template language ? 是否有使用ejs模板语言的干净方法?

I coulnd't find anything about it on the EJS official website, nor on sails website. 我在EJS官方网站或Sails网站上找不到任何相关信息。

I naively tried this until now : 我天真地尝试了到现在:

<% objects.forEach(function(object)  { %>
    <% if(object.someId == someValue) {%>
        <%= object.name %>
        <% break %> <!-- This raise an illegal statement exception -->
    <% } %>
<% } %>

The following code works as expected, but i'm looking for a cleaner solution if any 以下代码按预期工作,但我正在寻找更清洁的解决方案(如果有)

<% var found = false %>
<% objects.forEach(function(object)  { %>
    <% if(object.someId == someValue && !found) {%>
        <%= object.name %>
        <% found = true %>
    <% } %>
<% } %>

It's not an EJS-related question. 这不是与EJS相关的问题。

break statement terminates the current loop. break语句终止当前循环。 While you are not inside a loop. 当您不在循环中时。 You are inside callback function, that's called by forEach method once per array element. 您在回调函数内部,每个数组元素均由forEach方法调用一次。 There's no ability to interrupt forEach (see How to short circuit Array.forEach like calling break? ). 无法中断forEach(请参阅如何像调用break那样使Array.forEach短路? )。 But, if you need it, you may use for loop for a clean solution: 但是,如果需要,可以使用for循环获得干净的解决方案:

<% for (var l = objects.length, i = 0; i < l; i++) { %>
    <% object = objects[i]%>
    <% if(object.someId == someValue) {%>
        <%= object.name %>
        <% break %> <!-- This will work as expected -->
    <% } %>
<% } %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM