繁体   English   中英

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

[英]How to loop, concatenate and push content into an array in JavaScript

我试图动态生成一个数组并连接结果,而无需将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();  
}}

对于您想做什么我有些困惑,但是据我所能推断的,我可以推荐一些事情。 首先,您可以遍历数组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变量的浮点数(如上所示)是您要执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM