代码之家  ›  专栏  ›  技术社区  ›  John Strickler

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

  •  0
  • John Strickler  · 技术社区  · 16 年前

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

    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 回复  |  直到 16 年前
        1
  •  1
  •   BBonifield    16 年前

    我不相信这个插件可以让你访问这些信息,所以我建议你只需按摩你的数据来包含它。

    所以,如果coords已经如您所提到的那样设置好了,只需在它上面循环,并为每个项添加一个“key”属性。

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

    然后你可以用 ${key}

        2
  •  0
  •   Pramendra Gupta    16 年前

    你必须使用 “用于”

    例子

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

    输出0,1

        3
  •  0
  •   Community Mohan Dere    9 年前
    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