javascript 在meteor 中,有没有办法访问空格键中的数组索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21815713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In meteor is there a way to access array index in spacebars
提问by Bads
I am using meteor Shark branch.
我正在使用流星鲨鱼分支。
Is there a way to access array index inside each block helper in spacebars?
有没有办法访问空格键中每个块助手内的数组索引?
I am looking for something like this.
我正在寻找这样的东西。
{{#each humans}}
{{this.arrayIndex}}
{{/each}}
回答by David Weldon
meteor >= 1.2
流星 >= 1.2
Spacebars gained a lot of functionality in 1.2, including a native @index
. Helpers are no longer needed to solve this problem - you can simply do this:
空格键在 1.2 中获得了很多功能,包括原生的@index
. 不再需要助手来解决这个问题——你可以简单地这样做:
<template name="showHumans">
<ul>
{{#each humans}}
<li>{{@index}}: {{name}}</li>
{{/each}}
</ul>
</template>
meteor < 1.2
流星 < 1.2
I saw a similar example using template helpers in the meteor bookin the "animations" chapter. You can apply a map
to the humans cursor in order to add an index like so:
我在“动画”一章的流星书中看到了一个使用模板助手的类似示例。您可以将 amap
应用于人类光标以添加如下索引:
Template.showHumans.helpers({
humans: function() {
return Humans.find({}, {sort: {hotness: -1}}).map(function(human, index) {
human.rank = index;
return human;
});
}
});
<template name="showHumans">
<ul>
{{#each humans}}
<li>{{rank}}: {{name}}</li>
{{/each}}
</ul>
</template>
回答by elGusto
As taken from the spacebars documentation:
取自空格键文档:
You can use a special variable @index in the body of #each to get the 0-based index of the currently rendered value in the sequence.
您可以在 #each 的主体中使用特殊变量 @index 来获取序列中当前呈现值的从 0 开始的索引。
回答by outofambit
In Meteor 1.0.2.1, you can do the following:
在 Meteor 1.0.2.1 中,您可以执行以下操作:
{{#each humans}}
{{this}}
{{/each}}
This is because #each iterates through the array, making the this in each loop simply equal to the current value.
这是因为 #each 遍历数组,使每个循环中的 this 简单地等于当前值。