在Handlebars.js中循环使用多维数组

Looping through a multidimensional array in Handlebars.js

本文关键字:数组 循环 Handlebars js      更新时间:2023-09-26

我让服务器传回这个JSON,我不知道如何在Handlebars中循环遍历二维数组。

"userSurvey":[[1],[2],[3]]

我知道使用{{#each userSurvey}},但我该如何在usersurvey对象内执行数组呢?

您必须循环2次:

{{#each userSurvey}}
  {{#each this}}
    {{ this }}
  {{/each}}
{{/each}}

在这种特殊情况下,如果你只想渲染"123",你可以这样做:

{{#each userSurvey}}
    {{this.[0]}}
{{/each}}

或者更简单,因为数组自动转换为字符串:

{{#each userSurvey}}
    {{this}}
{{/each}}
    {{#each Arr}}
        {{#each this}}
            <label>{{this.[0]}}</label> {{this.[1]}}<br>
        {{/each}}
    {{/each}}

以下是我循环数组的简单示例:(

使用#with-helper对于目标

{ catg: [ 'java', 'c', 'c++' ],
  quesarray: [ [ 2, 1 ], [ 0, 2, 10, 5, 11, 12 ], [ 7, 5, 3, 8, 0 ] ],
  _id: 5d778d52d410984dc4e3e278,
  username: 'student@gmail.com' }

如果你想访问数组quesarray索引明智地做这个

{{#each qset}}
{{#with quesarray}}
{{[2]}}
{{/with}}
{{/each}}

输出将为7、5、3、8、0