开发者

How can I define variables in a for loop in javascript?

I'm trying to define variables within a loop. I'll drop the code here and then try and explain some more:

for (var k=0; k<nodes.length; k++){
    this[node+k] = new google.maps.Marker({
        position: new google.maps.LatLng(array1[k], arr开发者_运维百科ay2[k]),
        map: map,
        title: node[k],
        icon: "some image file"
    });
}

I would like to create a list of variables which are to be named sing an already defined array (the array of names is called nodes in the code above). So in this loop, I would like to define a new variable "this[node+k]" to make a new google.maps.marker variable.

The purpose is to make a bunch of markers with pop-ups on a custom google map for some management software I'm trying to write.

I'm sure there must be some way to do it because I saw other code for defining variables in a loop (Which ofcourse I can no longer find... :( ).However, the names of the variables being defined in the loop were not taken from another array (as mine are).

I don't want to create var1, var2, var3. I saw how to do that. I want to create these variables using names from an array.

I apologize if the question still isn't clear but thanks for the help so far. I have a feeling it may be the google maps code confusing the situation too. So here is the original way to define the google maps marker variable:

var NAME1= new google.maps.Marker({
    position: new google.maps.LatLng(29.70600, -95.28159), // coordinates
    map: map,
    title:"NAME1", // marker title
    icon: "http://127.0.0.1/public_html/tower.gif" // icon
});

The code I have right now just repeats this code 20+ times to define all the different variables. I want to try and put this all into a for loop and define the variables using names from an array.


In your for loop you should use semicolons instead of commas:

for (var k=0; k<nodes.length; k++){
     // ...
}


I am not sure what you are trying to do, but you might try:

var names = ["name1", "name2"];
var markers = new Array();
for (var k=0; k<names.length; k++){
    markers[k] = new google.maps.Marker({
        position: new google.maps.LatLng(array1[k], array2[k]),
        map: map,
        title: names[k],
        icon: "some image file"
    });
}


You can do what you describe if you create a variable outside of your for loop and then put your new creations into it. Something like this:

var maps = [];
for (var k=0; k<nodes.length; k++){
    maps[k] = new google.maps.Marker({
        position: new google.maps.LatLng(array1[k], array2[k]),
        map: map,
        title: node[k],
        icon: "some image file"
    });
}

That uses numeric keys on the maps array to keep track of the items. You can make maps an object instead and use text keys if that's better for your scenario.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜