检索具有有限信息的数组键(非关联)

时间:2010-09-20 14:44:33

标签: javascript jquery jquery-plugins

如何访问非关联数组的密钥?这是我的场景,我有一个对象数组(在这种情况下,它们是坐标):

coords[0] = {x: 37.543524, y: -56.65474}
coords[1] = {x: 35.041292, y: -76.03135}
//etc.. 

我正在使用jQuery templating plugin打印出结果:

$('#repeater').tmpl(coords).appendTo('body');

<script id="repeater" type="text/html">
  <p>[${key??}] ${x}, ${y}</p><br/>
</script>

在模板中,我可以访问对象属性,但不能访问索引。有没有一种简单的方法来检索数组中该对象的键?或者我是否必须修改插件才能访问它?

谢谢!

3 个答案:

答案 0 :(得分:1)

我不相信该插件会让您访问该信息,所以我建议您只是按摩您的数据以包含它。

因此,如果已按照您的提及设置了coords,只需将其循环并为每个项添加“key”属性。

for( var key in coords ) {
   coords[ key ].key = key;
}

然后,您可以在模板中使用${key}属性。

答案 1 :(得分:0)

您必须使用“for”

<强> 实施例

for(key in coords){
 alert(key);
}

输出0,1

答案 2 :(得分:0)

function index( item, array ) {
    return $.inArray( item, array ) + 1;
}

$('#repeater').tmpl({coords: coords}).appendTo('body');

<script id="repeater" type="text/html">
  {{ each coords }}
  <p>[${index($value, coords)}] ${x}, ${y}</p><br/>
  {{ /each }}
</script>

派生自this example