对象属性名称作为变量

时间:2016-06-10 10:40:51

标签: javascript

我在下面有这个代码,我试图制作属性名称" color"在" maps.setColors({"替换为来自drivers数组的值:

var drivers = {
    "drivers":[
       {
          "driver_id":"101",
          "driver_name":"B",
          "truck_capacity":1000,
          "truck_color":"#00FF00",
          "truck_radio":"checked"
       },
       {
          "driver_id":"102",
          "driver_name":"A",
          "truck_capacity":2000,
          "truck_color":"#FF0000",
          "truck_radio":""
       }
     ]
 };

for (var prop in drivers) { 
        if (drivers.hasOwnProperty(prop)) { 
            for (var prop2 in drivers[prop]) {
                var color = drivers[prop][prop2]['truck_color'];
                maps.setColors({
                    color: {
                        current: 0,
                        polygonOptions: {
                            fillColor: color,
                            fillOpacity: 0.7,
                            strokeColor: '#2143AA',
                            strokeWeight: 2,
                            suppressUndo: true
                        }
                    }
                });
                google.maps.event.addDomListener(document.getElementById(id), 'click', function() {
                    maps.setColor(color);
                });
            }
        }
    }

它没有那么基本,我希望循环动态生成这样的代码:

maps.setColors({
    '#00FF00': {
        current: 0,
        polygonOptions: {
            fillColor: '#00FF00',
            fillOpacity: 0.7,
            strokeColor: '#2143AA',
            strokeWeight: 2,
            suppressUndo: true
        }
    },
    '#FF0000': {
        current: 0,
        polygonOptions: {
            fillColor: '#FF0000',
            fillOpacity: 0.7,
            strokeColor: '#2143AA',
            strokeWeight: 2,
            suppressUndo: true
        }
    }
});

我该怎么办呢?

由于

2 个答案:

答案 0 :(得分:1)

这样的事情应该可以胜任:

var params = {};
for (var prop2 in drivers[prop]) {
    var color = drivers[prop][prop2]['truck_color'];
    params[color] = {
        current: 0,
        polygonOptions: {
            fillColor: color,
            fillOpacity: 0.7,
            strokeColor: '#2143AA',
            strokeWeight: 2,
            suppressUndo: true
        }
    };
}
maps.setColors(params);

答案 1 :(得分:0)

我认为你应该这样说:

void funkcija(int broj)
{

    char *niz;
    int i;

    niz = (char*)malloc(broj*sizeof(char));
    fillstring(niz, broj);

    //Use string here

    free(niz);
}

void fillstring(char *buffer, int len)

{
    int i;
    srand(time(NULL));

    for (i = 0; i < len; i++)
    {
        buff[i] = '0' + rand() % 10;
    }
}

用刹车。 请参阅此codepen中的控制台输出:http://codepen.io/anon/pen/vKGNbB?editors=1111