为什么#each标签不接受数组?

时间:2015-09-28 18:11:13

标签: javascript meteor spacebars

我的optionData.js如下:

"options"=
[
{
  "option_text": "Just Me",
  "option_image": "just-me.svg",
  "option_is_selected": false
},
{
  "option_text": "Spouse/Partner",
  "option_image": "spouse-partner.svg",
  "option_is_selected": false
},
{
  "option_text": "Child/Children",
  "option_image": "child-children.svg",
  "option_is_selected": false
},
{
  "option_text": "Grand Children",
  "option_image": "grandchildren.svg",
  "option_is_selected": false
},
{
  "option_text": "Parent(s)",
  "option_image": "parents.svg",
  "option_is_selected": false
},
{
  "option_text": "Pet(s)",
  "option_image": "pets.svg",
  "option_is_selected": false
},
{
  "option_text": "Anyone Else",
  "option_image": "anyone-else.svg",
  "option_is_selected": false
}
]

这是我的options.js文件

calc_option_set1: function(){
    var options_set = this.options;
    option_count = options_set.length;
    upperRowObjects = [];

    if(option_count == 2)
    {
        rowBreak = -1;
    }
    else if(option_count % 2 == 0)
    {
        rowBreak = (option_count / 2);
    }
    else
    {
        rowBreak = (option_count + 1) / 2;
    }

    for(i=0; i<rowBreak; i++)
        upperRowObjects = upperRowObjects + options_set[i];
    return upperRowObjects;
},

这是options.html

{{#each option_set1}}
<div class="col-xs-2">
    <center>
        <img src="/images/{{option_image}}" class="img-responsive img-rounded img-option"/>
        <h5>{{option_text}}</h5>
    </center>
</div>
{{/each}}

基本上我想划分选项并将它们呈现在两个不同的行(CSS)中。如果我打印{{calc_option_set1}},我会得到我想要的对象集。 但是,如果我尝试在代码中迭代它们,我会得到错误

  

&#34;未捕获错误:{{#each}}目前只接受数组,游标或   虚假的价值观。&#34;

如何迭代方法返回的数组?我可以用任何方式将它分配给变量然后使用它吗?请帮忙......

1 个答案:

答案 0 :(得分:2)

数组连接不适用于+运算符。改为使用Array.push()。

calc_option_set1: function(){
    var options_set = this.options;
    option_count = options_set.length;
    upperRowObjects = [];

    if(option_count == 2)
    {
        rowBreak = -1;
    }
    else if(option_count % 2 == 0)
    {
        rowBreak = (option_count / 2);
    }
    else
    {
        rowBreak = (option_count + 1) / 2;
    }

    for(i=0; i<rowBreak; i++)
        upperRowObjects.push(options_set[i]);
    return upperRowObjects;
},

并通过以下方式访问它:

{{#each calc_option_set1}}
{{/each}}