【发布时间】:2018-05-05 16:17:44
【问题描述】:
我一直在使用 javascript 来运行一些使用 leaflet.js 库的简单代码(在本例中,特定函数是 mymap.layerPointToLatLng(), here is the documentation )。 我想使用 [[[x,y]],[[x,y]],...] 形式的一些数据(该格式特别适用于 Leaflet.js 如何处理多边形和多多边形,这种格式是我称之为'dim = 2')。我需要将其转换为纬度和经度(因此是前面提到的函数)。因为我经常这样做,所以我写了一个函数来为我做这件事:
/*-Formatting functions*/
function coordconvert(mapvar,array,dim){
var temp1in=[],tempout1=[],temp2out=[];
if(dim===1){
for(i=0;i<array.length;i++){
tempout1[i]=mapvar.layerPointToLatLng(array[i]);
}
return tempout1;
}
else if(dim===2){
for(i=0;i<array.length;i++){
temp1in=array[i];//each polygon
console.log(i);
console.log(temp1in);
console.log(tempout1);
//tempout1=[];//why do I need this line?
for(j=0;j<temp1in.length;j++){
console.log(tempout1);
var checking = mapvar.layerPointToLatLng(temp1in[j]);
tempout1[j]=mapvar.layerPointToLatLng(temp1in[j]);//each vertex of polygon
console.log(j);
console.log(tempout1);
console.log(checking);
}
temp2out[i]=tempout1;//array of polygons
}
return temp2out;
}
else{
console.log("Unable to process coordinate conversion on array");
return
}
}
但是,“if(dim===2)”部分似乎无法正常工作,因此所有 console.log 行都无法正常工作。
特别是,如果我取消注释 //tempout1=[];//why do I need this line? 行,分配 tempout1[j]=mapvar.layerPointToLatLng(temp1in[j]); 似乎才有效。
使用 console.log 并使用 Google Chrome 查看,我得到以下输出:
First few iterations of loop Final iteration of the loop
所以可以看出,在分配任何东西之前,最终迭代的值(一个对象)被包含在 tempout1 的数组中(我尝试删除 'if(dim===1 )' 部分,并重命名 tempout1 变量,没有运气),并且被 Chrome 隐藏(?!?!?!);该值在循环期间没有被覆盖(通过比较console.log(checking) 和console.log(tempout1) 可以看出。
为什么每次在嵌套循环运行之前都必须清理变量?为什么最终迭代的价值会在任何事情发生之前就进入?
【问题讨论】:
标签: javascript arrays for-loop variable-assignment nested-loops