【问题标题】:Inside Express/EJS templates, what is cleanest way to loop through an array?在 Express/EJS 模板中,循环数组的最简洁方法是什么?
【发布时间】:2013-04-15 17:24:26
【问题描述】:

我有一个使用 EJS 模板设置的 Express.js 应用程序。我用经典的 JS 语法成功循环了一个数组:

<% for (var i = 0; i < myArray.length; i++) { 
    this = myArray[i];
    // display properties of this
} %>

但我想知道,有没有更清洁的方法来做到这一点?

具体来说,我可以使用 Underscore 或 Lodash 循环遍历 .each 吗?谢谢

【问题讨论】:

    标签: node.js express underscore.js ejs partials


    【解决方案1】:

    你可以使用forEach方法

    myArray.forEach(function(el, index) {
        // el - current element, i - index
    });
    

    【讨论】:

    • 但是当我删除数组中的一个元素时,索引将无法适应。对此有什么解决方案?
    • @Emanuelacolta 您不能在 forEach 中删除您的项目。您应该将要删除的元素的索引保存在单独的数组中,并在完成 forEach 后删除它们。 (并且您需要以相反的顺序删除它们,以便数组的索引在您删除时不会移动)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2020-10-03
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    相关资源
    最近更新 更多