【问题标题】:How to iterate through nested arrays with jsredner如何使用 jsredner 遍历嵌套数组
【发布时间】:2012-11-29 00:56:49
【问题描述】:

我有以下 json:

[
   {
      "Name":"Billy in the Lowground",
      "Key":"A",
      "chords":[
         [
            "G",
            "",
            "D",
            ""
         ],
         [
            "C",
            "",
            "G",
            ""
         ],
         [
            "C",
            "",
            "G",
            ""
         ],
         [
            "A",
            "",
            "D",
            ""
         ],
         [
            "G",
            "",
            "D",
            ""
         ],
         [
            "C",
            "",
            "G",
            ""
         ],
         [
            "C",
            "",
            "G",
            ""
         ],
         [
            "D",
            "",
            "G",
            ""
         ],
         "Em",
         "",
         "",
         "B7",
         "Em",
         "",
         [
            "C",
            "",
            "G",
            ""
         ],
         [
            "D",
            "",
            "G",
            ""
         ]
      ]
   }
];

在和弦下,我将每个小节映射到和弦数组中的一个点,然后每个小节是另一个数组,对应于小节中的节拍数。在本例中为 4 拍。

所以我在弄清楚如何迭代嵌套数组时遇到了问题,但是当我写这个问题时,我想我找到了答案,但这是访问和迭代嵌套数组的最佳方式吗:

 <script id="chord-tpl" type="text/x-jsrender">  
                {{for chords}}
                    <tr>
                        {{for #parent.data[#index]}}

                            <td>{{:#parent.data[#index]}}</td>
                        {{/for}}
                    </tr>
                {{/for}}

        </script>

另外我想知道是否有一种方法可以查看您对数组进行了多少次迭代并根据 # 次执行某些操作,

例如

for( i=0; i == chords.length; $i++ ) {
   if( i % 4 ) {
       // start new table row
   }
   else {
       // echo out table cell
   }
}

【问题讨论】:

    标签: jquery arrays nested jsrender


    【解决方案1】:

    这是访问和迭代嵌套数组的最佳方式吗

    您可以将您的模板修改为:

    {{for chords}}
        <tr>
           {{for #data}}
               <td>{{:#data}}</td>
           {{/for}}
        </tr>
    {{/for}}
    

    我想知道是否有一种方法可以查看您对数组进行了多少次迭代并根据 # 次做某事

    您允许引入一个变量。

    {{for chords ~count=chords.length}}
    

    更多详情您可以找到here


    您还可以使用"helper functions" 调试您的模板 这个sn-p可以帮到你

    $.views.helpers({
      debug:function(){
         console.dir(this);
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2017-05-13
      • 2017-09-08
      • 1970-01-01
      相关资源
      最近更新 更多