如何在JavaScript中循环,连接和将内容推送到数组中

时间:2014-10-02 14:53:20

标签: javascript arrays string concatenation push

我尝试动态生成数组并连接结果而不将google maps函数转换为字符串。

有关最佳方法的任何建议都会很棒。

以下是我的代码片段:

function goCheck() { // find out what checkboxes in the form were selected

//set a few variables and arrays
var input = document.getElementsByTagName('input');
var checkboxCount = 0;
var selections = [];
var urlArray = [];

// 1st loop to get form checkbox selections
for (var i=0, length = input.length; i<length; i++) { 
     if (input[i].checked === true) {
     s = input[i].value;
     selections.push(s); // store values for checkbox selections in array
     checkboxCount++; // keep track how many were checked

     var url = "https://mywebsite.ca/" + s + ".txt";
     urlArray.push(url); // store urls in array
   }
}

console.log(checkboxCount); // number of boxes checked
console.log(selections); // array with the selections
console.log(urlArray); // an array with the json urls

// 2nd Loop  - iterate over URL array and call function to get json object

var xmlhttp;
var myArr;
for (var i=0, length = urlArray.length; i<length; i++) {
    xmlhttp = new XMLHttpRequest(); //
    console.log(xmlhttp);
    xmlhttp.onreadystatechange = function() { 
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
              var myArr = JSON.parse(xmlhttp.response);

              console.log(myArr);
              console.log(myArr[selections[i]]);
              console.log(myArr[selections[i]].length); 


/* this is where I'm getting into trouble ----->


              var arraySize = (myArr[selections[i]].length); 
              for(k=0; k<arraySize; k++) {  
              district = "new google.maps.LatLng("+myArr[selections[i]][0]+")"; 
              polyLayer.push(district);


 <----- */  

         }
       } 
    };

    xmlhttp.open("GET", urlArray[i], false);
    xmlhttp.send();  
}}

1 个答案:

答案 0 :(得分:1)

我对你想做什么感到有点困惑,但从我能推断的最好的情况来看,我可以推荐一些东西。首先,您可以循环遍历数组polyLayer用其评估对象替换字符串:

polyLayer.forEach(function (element, index, array) {
    array[index] = eval(element);
});

不要这样做。您可以将代码暴露给很多危险,因为eval可能会运行恶意或意外的代码,只需在polyLayer中添加一个字符串即可。

否则,为避免首先出现字符串问题,请将district设置为等于评估对象。将myArr[selections[i]][0]修改为您需要的两个数字:

var n = myArr[selections[i]][0].split(",");
district = new google.maps.LatLng( parseFloat(n[0]), parseFloat(n[1]) );

修改

感谢您添加更多代码,并重新提问。我仍然认为拆分和解析myArr[selections[i][0]]用于创建district变量的浮点数(如上所示)是你想要做的。