开发者

Retrieving an array key (non-associative) w/ limited information

How can I access the key of a non-associate array? Here's my scenario, I have an array of objects (in this case, they are coordinates):

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

I'm using a jQuery templating plugin to print out the results:

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

<script id="repeater" type="text/html"开发者_StackOverflow社区>
  <p>[${key??}] ${x}, ${y}</p><br/>
</script>

In the template, I have access to the object properties but not the index. Is there an easy way to retrieve the key of that object in the array? Or would I have to modify the plug-in to give me access to it?

Thanks!


I don't believe that plugin gives you access to that information, so I'd suggest you just massage your data to include it.

So if coords is already set as you mentioned, just loop over it and add a 'key' property to each item.

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

Then you can use the ${key} property in your templates.


You have to use "for"

Example

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

output 0,1


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>

Derived from this example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜