2012-11-29 32 views
0

迭代我有以下JSON:如何通过嵌套阵列与jsredner

[ 
    { 
     "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 
    } 
} 

回答

2

这是最好的方式来访问和遍历嵌套数组

您可以通过修改模板,以这样的:

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

我想知道如果有办法看看你有多少次迭代arr ay并根据#时间做些什么

您允许引入一个变量。

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

更多细节,你可以找到here


你也能够与"helper functions" 调试您的模板,这个片段可以帮助您

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