Javascript:在循环内生成对象键并将对象数组推入每个对象中?

时间:2011-09-15 16:28:08

标签: javascript google-maps object hash key

我在这里处理Google地图:http://crocdoc.ifas.ufl.edu/projects/chameleonmapdev/

我有以这种格式设置标记的数据:

var nights = ['July1211', 'July1411'];
var waypoint_data = {
    July1211: [
        //Lat, long, j/a (juvenile/adult)
        [25.429363, -80.508326, j],
        [25.429332, -80.508216, j]
    ],

    July1411: [
        [25.42936, -80.51023, j], 
        [25.42936, -80.51036, j]

    ]
};

构建点的函数如下所示:

function buildPoints() {
    //var marker_container = new Object;

        for ( i = 0; i < nights.length ; i++ ) {

            //Loop for each data point that night
            for ( h = 0; h < waypoint_data[nights[i]].length; h++) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(waypoint_data[nights[i]][h][0], waypoint_data[nights[i]][h][1]),
                    icon: waypoint_data[nights[i]][h][2],
                    shape: pointshape,
                    map: map
                });

                //Push waypoints into date-specific object key
                //marker_container[nights[i]].push(marker);

            }

        }

    }   

我想将每个日期(night [i])的标记推入另一个对象键,以便隐藏/显示特定的夜晚标记。我已经尝试用我注释掉的两个marker_container行来做这个,但是它们只是打破了我的循环,而在Firebug中,我得到一个关于marker_container [nights [i]]未定义的错误。 nights [i]是一个字符串,所以我认为这种语法可行。任何提示都非常感谢,我非常乐意为其他更好的方法编写代码。

2 个答案:

答案 0 :(得分:2)

您不能在对象上使用push,仅在数组上使用function buildPoints() { var marker_container = new Object(); for ( i = 0; i < nights.length ; i++ ) { marker_container[nights[i]] = new Array(); //Loop for each data point that night for ( h = 0; h < waypoint_data[nights[i]].length; h++) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(waypoint_data[nights[i]][h][0], waypoint_data[nights[i]][h][1]), icon: waypoint_data[nights[i]][h][2], shape: pointshape, map: map }); //Push waypoints into date-specific object key marker_container[nights[i]].push(marker); } } } 。我想这就是你想要做的事情:

{{1}}

simple proof of concept jsfiddle

答案 1 :(得分:0)

如果你知道你将拥有多少个标记(比方说10),设置标记容器,使对象的每个元素成为一个对象本身,长度为2:

    marker_container= new Object(10);
       for (i=0; i<marker_container.length; i++){
          marker_container[i]=new Object(2);
       }

创建标记后,将它们添加到marker_container:

  marker_container[i][0] = nights[i];
  marker_container[i][1] = marker;

如果要显示和隐藏标记,请执行以下操作:

  //display
  marker_container['nightX'].setMap(map);

  //hide
  marker_container['nightX'].setMap(null);