Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用循环索引访问把手阵列_Javascript_Arrays_Handlebars.js - Fatal编程技术网

Javascript 使用循环索引访问把手阵列

Javascript 使用循环索引访问把手阵列,javascript,arrays,handlebars.js,Javascript,Arrays,Handlebars.js,我正在使用handlebar.js迭代类别,然后使用当前数组索引访问系列数组中的元素。我可以使用下面的助手来执行此操作 var json={ "categories": [{ "id": 3, "name": "category 0" }, { "id": 6, "name": "category 1" } ], "series": [{

我正在使用handlebar.js迭代
类别
,然后使用当前数组索引访问
系列
数组中的元素。我可以使用下面的助手来执行此操作

var json={
    "categories": [{
            "id": 3,
            "name": "category 0"
        }, {
            "id": 6,
            "name": "category 1"
        }
    ],
    "series": [{
            "id": 1,
            "name": "DUMMY",
            "data": [{
                    "id": 5,
                    "name": "series 0 data 0"
                }, {
                    "id": 10,
                    "name": "series 0 data 1"
                }
            ]
        }
    ]
}

Handlebars.registerHelper('getArrayValues', function(ar, index, prop) {
    return ar[0].data[index][prop];
});

var template = Handlebars.compile(json);

{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id with helper: {{getArrayValues ../series @index 'id' }}</p>
<p>series name with helper: {{getArrayValues ../series @index 'name' }}</p>
{{/each}}

我为此找到了一个解决方案,我不知道它有多好,但它工作得非常完美

试试这个:)

{{{#每个类别}
id:{{this.id}

名称:{{this.name}

带有帮助程序的序列id:{{#with(lookup../series.[0]。数据 @索引)}{{this.id}{{{/with}}

具有帮助程序的系列名称:{{#with(lookup../series.[0]。数据 @索引)}{{this.name}{{{/with}}

{{/每个}}
谢谢Nishant,虽然我确信您的答案是准确的(但尚未测试),但我可能会坚持使用我的愚蠢助手函数,因为它对我有意义。编辑可能会改为您的。经过测试,效果完美。我在上找到了带有文档的
#。谢谢
{{#each categories}}
<p>id: {{this.id}}</p>
<p>name: {{this.name}}</p>
<p>series id: {{../series.[0].data.[@index].id}}</p>
<p>series name: {{../series.[0].data.[@index].name}}</p>
{{/each}}
{{#each categories}}
  <p>id: {{this.id}}</p>
  <p>name: {{this.name}}</p>
  <p>series id with helper:{{#with (lookup  ../series.[0].data 
  @index) }}{{this.id}}{{/with}}</p>
  <p>series name with helper: {{#with (lookup  ../series.[0].data 
  @index) }}{{this.name}}{{/with}}</p>
{{/each}}