如何在for循环中将var定义为对象

时间:2014-08-09 23:43:47

标签: javascript

我有一种情况,我想迭代多边形,它的名字有点像这样

 for key in result:
            my_poly.push ( map.drawPolygon({
                paths: key.poly_points,
                title: key.name,
                draggable: true,
                editable: true,
                strokeColor: 'black',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#FF0000',
                fillOpacity: 0.35,
                click: function(e) {
                    alert('You clicked ' + my_poly.title);
                }

           });
        )

从这样的结果

{"poly1":{"name":"a1","poly_points":[[47.5318968167,7.70495563751],
                                      [47.5320376772,7.70489126449],    
                                      [47.5317713226,7.70478934055],                    
                                      [47.5318968167,7.70495563751]]}}

如果我迭代结果,键值是poly1及其字符串,但我希望它是一个obj来获取poly1的内部数组中的值,如下所示

 key.name=a1,
 key.poly_points= [[47.5318968167,7.70495563751],                       
              [47.5320376772,7.70489126449],    
              [47.5317713226,7.70478934055],                   
              [47.5318968167,7.70495563751]]

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

要使用result[key]

访问循环中的当前项目
 for (var key in result){
        my_poly.push ( map.drawPolygon({
            paths: result[key].poly_points,
            title: result[key].name,
            draggable: true,
            editable: true,
            strokeColor: 'black',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35,
            click: function(e) {
                alert('You clicked ' + this.title);
            }

       })
    )}