如何从其他变量中获取价值

时间:2011-12-25 05:24:17

标签: javascript

如何从JavaScript中的其他变量中获取值?

<script type="text/javascript"> <!--

    var lat0 = 10.212; 
    var lat1 = 11.9090; 
    var lat2 = 12.12;

    var lon0 = 10.212; 
    var lon1 = 11.9090; 
    var lon2 = 12.12;

    var lat = new Array("lat"+i); 
    var lon = new Array("lon"+i);

    for (var i = 0; i < 2; i++) {   
        lat[i] = "lat"+i;   
        lon[i] = "lon"+i;       
        document.write(lat[i]);     
        document.write(" ");    
        document.write(lon[i]);     
        document.write(" "); 
    }
    //--> 
</script>

我想得到lat0,lat1,lat2,lon0,lon1,lon2值。

1 个答案:

答案 0 :(得分:3)

通常情况下,我建议您使用bracket notation,但确实从一开始就使用正确的数据结构:

var positions = [
    {lat: 10.212, lon: 10.212},
    {lat: 11.9090, lon: 11.9090},
    {lat: 12.12, lon: 12.12}
];

var pos;

for (var i=0; i<positions.length; i++) {
    pos = positions[i];
    document.write(pos.lat + ' ' + pos.lng + ' ');
}
使用document.write N.B。 非常 明智。使用DOM操作几乎总是更好。见Why is document.write considered a "bad practice"?